c ++问题将信息传递给pthreads

c++ issue passing information to pthreads

我遇到的问题是 showData() 中的 printf 调试语句会给我无意义的数字。即:thread_id 是 -1781505888。 如果我在设置 thread_id、startIndex 和 stopIndex 的值后立即在 createThreads() 中插入 printf 语句,那么这些值将正确打印。当我将 threadData 作为参数传递给 pthread_create 或当我在 showData() 中从 threadArg 读取数据时,数据不知何故被破坏。此外,N 和 k 的值可以假设为整数,N/k 的余数为 0。感谢所有帮助。

编辑:另外,如果它提供了任何额外信息——当我 运行 在同一个输入上执行此操作时,我每次 运行 都会得到不同的输出。有时是无意义的数字,有时所有值都打印为 0,有时它会出现错误。

void createThreads(int k){
struct threadData threadData;
int numThreads = k;
int i = 0;
int err = 0;

pthread_t *threads = static_cast<pthread_t*>(malloc(sizeof(pthread_t) * numThreads));
for(i = 0;i<numThreads;i++){
    struct threadData threadData;
    threadData.thread_id = i;
    threadData.startIndex = ((N/k)*i);
    if(i == numThreads -1){
        threadData.stopIndex = ((N/k)*(i+1))-1;
    }
    else{
        threadData.stopIndex = ((N/k)*(i+1));
    }



    err = pthread_create(&threads[i], NULL, showData, (void *)&threadData); 


    if(err != 0){
        printf("error creating thread\n");
    }
}
}

void *showData(void *threadArg){
    struct threadData *threadData;
    threadData = (struct threadData *) threadArg;

    printf("thread id : %d\n", threadData->thread_id);
    printf("start: %d\n", threadData->startIndex);
    printf("stop : %d\n", threadData->stopIndex);
}

threadData 是您的 for 循环的本地...它在每次迭代时超出范围,因此指向它的指针在您的 showData() 例程中无效。您可以改为动态分配它并 delete 它在 showData.

的末尾

您可能还想 return threads 数据给 createThreads' 调用者,因此它可以 join 线程等待 showData "work".

示例:

...
for(i = 0; i < numThreads; ++i)
{
    struct threadData* threadData = new struct threadData;
    threadData->thread_id = i;
    threadData->startIndex = ((N/k)*i);
    if(i == numThreads -1){
        threadData->stopIndex = ((N/k)*(i+1))-1;
    }
    else{
        threadData->stopIndex = ((N/k)*(i+1));
    }

    err = pthread_create(&threads[i], NULL, showData, (void*)threadData); 

    if(err != 0){
        printf("error creating thread\n");
        exit(1); // probably not worth trying to continue...
    }
    return threads;
}

void *showData(void *threadArg){
    struct threadData* threadData = (struct threadData*)threadArg;

    printf("thread id : %d\n", threadData->thread_id);
    printf("start: %d\n", threadData->startIndex);
    printf("stop : %d\n", threadData->stopIndex);

    delete threadData;
}