0

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

0 回答 0