使用eclipse 64位在MinGW 32上进行pthread

时间:2014-12-27 10:02:24

标签: c++ mingw pthreads-win32

我有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;
}

0 个答案:

没有答案