如何使用从线程函数返回到主函数的struct指针?

时间:2019-03-24 15:18:48

标签: c pthreads pthread-join

我正在编写一个将整数用作命令行参数的程序。对于这些数字中的每一个,我必须创建一个线程,该线程将计算该数字之前的斐波那契数列。该函数将结构指针返回到打印数据的主要位置。

现在,我已经正确完成了fib计算并通过在函数中打印序列来检查了它们。

当我尝试返回在线程函数中创建的struct指针并使用它来打印主数据时,就会出现问题。

typedef struct thread_func_param
{
    int *fib;
    int size;
} thread_func_param;
//===================================================    
void *fibGen(void *parameters)
{
    int num = atoi(parameters);
    struct thread_func_param *p;
    p = malloc (sizeof (thread_func_param));

    p->size = fibSize(num);
    p->fib = malloc(sizeof(int)* p->size);

    //Fibonacci Calculations
    //..
    //.

    return (void *) p;
    //pthread_exit((void *) p);
}
//=================================================== 
int main(int argc, char* argv[])
{
    void* thread_result;
    thread_func_param* p = malloc( sizeof(thread_func_param));
    assert(argc > 1);

    int noOfThreads = argc - 1;
    printf("No of Thread = %d\n", noOfThreads);
    pthread_t *threadID = malloc (sizeof (pthread_t) * noOfThreads);

    pthread_attr_t attributes;
    pthread_attr_init(&attributes);

    int i, j;
    for(i = 0; i < noOfThreads; i++)
    {
        pthread_create(&threadID[i], &attributes, fibGen, argv[i+1]);
        pthread_join(threadID[i], thread_result);


        //HOW TO USE THE RETURNED DATA?
        for (j = 0; j< ((thread_func_param*)thread_result->size)-1; j++)
        printf(" %d ", (thread_func_param*)thread_result->fib[j]);
    }

    return 0;
}

最后,我用来打印数据的解决方案给出了取消引用空指针的错误(我是C的新手)。我该如何纠正?

1 个答案:

答案 0 :(得分:2)

这里有两个问题:

  1. pthread_join()void**作为第二个参数。该代码仅传递void*
  2. 要投射指针,请将其包装在括号中。在这里

    (thread_func_param*)thread_result->size
    

    size而不是thread_result。所以你想要的是

    ((thread_func_param*)thread_result)->size
    

但是,一个不错且干净的解决方案只会临时使用void指针。看起来可能像这样:

int main(int argc, char* argv[])
{
  thread_func_param* thread_result;

  ...

    ...

    pthread_create(&threadID[i], &attributes, fibGen, argv[i+1]);

    {
      void * pv; 
      pthread_join(threadID[i], &pv);
      thread_result = pv;
    }

    if (NULL != thread_result) /* perform some sanity checking. */
    {
      for (j = 0; j < thread_result->size - 1; j++)
        printf(" %d ", thread_result->fib[j]);
    }

    ...