Pthread_create() 不正确的启动例程参数传递

Pthread_create() incorrect start routine parameter passing

我的 C++ 应用程序中的 pthreads 有问题。

在我的主要功能中我有:

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

    ...
}

在我的 thread_body 函数中:

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

    ...
}

此输出(例如 numberOfThreads=2)似乎是:

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

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

tid: 2924010304 no.thread: 1

tid: 2932403008 no.thread: 1

在更一般的情况下,对于所有线程,当 numberOfThreads=n 时,no.thread 等于 n-1。 你能帮我弄清楚为什么吗?关于您如何使用启动例程,有什么我不明白的地方吗?

感谢您的宝贵时间。

您的代码中有一个 data race,因为您将同一位置 (arg[0]) 的地址传递给此处的所有线程:

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

您可能打算使用:

   arg[i]=i;

相反。这同样适用于您在循环中进行的打印。