pthread_join导致seg错误

时间:2012-09-08 21:19:00

标签: join pthreads

作为pthreads教程练习的一部分,我编写了一个程序来创建10个线程,而不是加入10个线程。该程序运行并打印输出,但似乎在第一次调用pthread_join时会导致分段错误。我不确定为什么会这样。我尝试在网上搜索,但是大多数关于传递给函数的无效指针的问题。我不确定这是否与我的代码存在同样的问题,因为我没有轻易看到它。

如果有人可以帮助我,我当然会很感激:)

代码如下:

#include <stdio.h>
#include <pthread.h>
#define NTHREADS    10

void *thread_function(void *arg)
{
    int i;
    int *coming = (int*) arg;
    for(i=0; i<5; i++)
        printf("Hello, World (thread %d)\n", *coming);
    return NULL;
}

int main(void)
{
    int i;
    void *exit_status;
    int retVal;
    pthread_t pthread_array[NTHREADS];
    int randVals[10] = {23,5,17,55,9,47,69,12,71,37};

    printf("threads are created\n");
    for(i=0; i<10; i++)
    {
        retVal=pthread_create(&pthread_array[i], NULL, thread_function, &randVals[i]);
        printf("pthread_create %d retVal=%d\n", i, retVal);
    }

    printf("threads are joined\n");
    for(i=0; i<10; i++)
    {
        retVal= pthread_join(pthread_array[i], &exit_status);
        printf("pthread_join %d retVal=%d and exit_status=%d\n", i, retVal,
        *((int *)exit_status));
    }

    printf("all threads have ended\n");
    return 0;
}

2 个答案:

答案 0 :(得分:0)

这是问题

printf("pthread_join %d retVal=%d and exit_status=%d\n", i, retVal,
    *((int *)exit_status));

你的线程函数返回NULL,因此这是存储在exit_status中的值。所以现在在printf你做这个

*((int *)exit_status

您正在将此NULL指针转换为int *,然后将其解除引用。取消引用NULL指针不是一个好主意。有关如何使用exit_status What does exactly the "status" in pthread_join represent and how to query it

的更全面示例,请参阅此问题

答案 1 :(得分:0)

    *((int *)exit_status));

如果线程函数返回NULL(它确实如此),则会尝试取消引用它。在此之前,您应该测试exit_status

pthread_join(...);
if (exit_status != NULL)
    /* Safe to use. */
相关问题