Pthread_create() incorrect start routine parameter

2020-05-06 10:36发布

I have a problem with pthreads in my C++ application.

In my main function I have:

int main(){
    ...

    for(i=0; i<numberOfThreads; i++){
        arg[0]=i;
        pthread_create(&tidVec[i], NULL, &thread_body, (void*) arg);
        cout << "tidVec[" << i <<"]: " << tidVec[i] << " arg[0]: " << arg[0] << endl;
    }

    ...
}

And in my thread_body function:

void * thread_body(void* arg){
    ...
    int* a = (int*)arg;
    cout << "tid: " << pthread_self() << " no.thread: " << a[0] << endl;

    ...
}

The output to this (e.g. with numberOfThreads=2) appears to be:

tidVec[0]: 2932403008 arg[0]: 0

tidVec[1]: 2924010304 arg[0]: 1

tid: 2924010304 no.thread: 1

tid: 2932403008 no.thread: 1

In a more general case, with numberOfThreads=n, no.thread is equal to n-1, for all threads. Could you please help me figure out why? Is there something I don't understand in how you use the start routine?

Thank you for your time.

1条回答
唯我独甜
2楼-- · 2020-05-06 11:22

There's a data race in your code since you pass the address of the same location (arg[0]) to all threads here:

    arg[0]=i;
    pthread_create(&tidVec[i], NULL, &thread_body, (void*) arg);

You probably meant to use:

   arg[i]=i;

instead. And the same applies to prints you do in the loop.

查看更多
登录 后发表回答