较小的程序可以正常工作,但是一旦我开始编写30行以上,xcode似乎就想执行,但是什么也没有发生。这是我编写的代码,找不到任何错误,但是也许我的问题得到了解释。 `
using namespace std;
int errorCounter = 0;
class Vector
{
public:
Vector(unsigned int size = 10000) : size_(size)
{
vector_ = new int[size_];
set(0);
}
~Vector()
{
delete[] vector_;
}
bool setAndTest(int n)
{
set(n);
return test(n);
}
private:
void set(int n)
{
for(unsigned int i=0; i<size_; i++) vector_[i] = n;
}
bool test(int n)
{
for(unsigned int i=0; i<size_; i++) if(vector_[i] != n) return false;
return true;
}
int* vector_;
unsigned int size_;
};
Vector vec;
int threads = 50;
void *writer(void *ptr)
{
int *threadIDconvert = (int*)(ptr);
while(1)
{
if (!vec.setAndTest(*threadIDconvert)) {
errorCounter++;
cout<<"error arrised from thread ID " << *threadIDconvert << " error number" << errorCounter<<endl;
usleep(100000);
}
}
return NULL;
}
int main() {
//int threads;
//cout << "enter an amount of threads: min 1 max 100" <<endl;
//cin>>threads;
if(threads<1){cout<<"you screwed up"<<endl; return 0;}
else if (threads>100) {cout<<"you screwed up"<<endl; return 0;}
pthread_t threadID[threads];
for (int x=0; x<=threads; x++) {
pthread_create(&threadID[x], NULL, writer, &vec);
}
for (int CID=0; CID<=threads; CID++) {
pthread_join(threadID[CID], NULL);
}
return 0;
}
`
希望有人可以帮忙,对不起我没有展示我所有的包含物,我也不知道如何在堆栈上溢出(而且我知道我可以使用互斥体,但不能,这只是一个尝试)程序:-))