我有MinGW32并在eclipse上使用pthread构建一小段代码。代码成功编译和链接,但在使用非零退出值运行时终止。此处没有任何警告。但是,在调试它时,它工作正常。请咨询。
#include <iostream>
#include <pthread.h>
using namespace std;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
void* increment(void* counter)
{
cout << "increment" << endl;
int* pcounter = (int*)counter;
for(int i =0; i < 30000; ++i)
{
cout << "Inside for loop" << endl;
pthread_mutex_lock(&counter_mutex);
++(*pcounter);
pthread_mutex_unlock(&counter_mutex);
}
}
int main()
{
pthread_t arr[5];
int counter =0;
for(int i=0; i < 5; ++i)
{
cout << "Creating thread: " << i << endl;
int rc = pthread_create(&arr[i], NULL, increment, (void*)&counter);
if(rc != 0)
{
cout << "Error creating thread: " << rc << endl;
exit(0);
}
}
for(int i=0; i < 5 ; ++i)
{
pthread_join(arr[i], NULL);
}
cout << "result: " << counter << endl;
return 0;
}