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

时间:2015-03-16 00:31:14

标签: c++ pthreads corruption

我遇到的问题是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);
}

1 个答案:

答案 0 :(得分:2)

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

您可能希望将threads数据返回createThreads&#39;调用者也是如此,因此它可以join线程等待完成showData&#34;工作&#34;。

示例:

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