How to return a value from pthread threads in C?

后端 未结 8 2216
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 03:16

I\'am new to C and would like to play with threads a bit. I would like to return some value from a thread using pthread_exit()

My code is as follows:

8条回答
  •  一向
    一向 (楼主)
    2020-11-27 03:45

    Here is a correct solution. In this case tdata is allocated in the main thread, and there is a space for the thread to place its result.

    #include 
    #include 
    
    typedef struct thread_data {
       int a;
       int b;
       int result;
    
    } thread_data;
    
    void *myThread(void *arg)
    {
       thread_data *tdata=(thread_data *)arg;
    
       int a=tdata->a;
       int b=tdata->b;
       int result=a+b;
    
       tdata->result=result;
       pthread_exit(NULL);
    }
    
    int main()
    {
       pthread_t tid;
       thread_data tdata;
    
       tdata.a=10;
       tdata.b=32;
    
       pthread_create(&tid, NULL, myThread, (void *)&tdata);
       pthread_join(tid, NULL);
    
       printf("%d + %d = %d\n", tdata.a, tdata.b, tdata.result);   
    
       return 0;
    }
    

提交回复
热议问题