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

c++ issue passing information to pthreads

本文关键字:pthreads 信息 问题 C++      更新时间:2023-10-16

我遇到的问题是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 threadn");
    }
}
}
void *showData(void *threadArg){
    struct threadData *threadData;
    threadData = (struct threadData *) threadArg;
    printf("thread id : %dn", threadData->thread_id);
    printf("start: %dn", threadData->startIndex);
    printf("stop : %dn", threadData->stopIndex);
}

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

您可能还希望将threads数据返回给createThreads ' 调用方,以便它可以join线程以等待showData"工作"完成。

例:

...
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 threadn");
        exit(1); // probably not worth trying to continue...
    }
    return threads;
}
void *showData(void *threadArg){
    struct threadData* threadData = (struct threadData*)threadArg;
    printf("thread id : %dn", threadData->thread_id);
    printf("start: %dn", threadData->startIndex);
    printf("stop : %dn", threadData->stopIndex);
    delete threadData;
}