温馨提示×

C语言怎么获取线程返回值

小亿
199
2023-11-29 19:39:22
栏目: 编程语言
C语言开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C语言中,线程的返回值可以通过使用pthread_join函数来获取。pthread_join函数的原型如下:

int pthread_join(pthread_t thread, void **retval);

pthread_join函数将会阻塞调用线程,直到指定的thread线程结束。当指定的线程结束后,其返回值将会被存储在retval指针所指向的位置中。

下面是一个使用pthread_join函数获取线程返回值的例子:

#include <stdio.h>
#include <pthread.h>

void *thread_function(void *arg) {
    int *value = (int *)arg;
    *value = 10;
    return NULL;
}

int main() {
    pthread_t thread_id;
    int thread_arg = 0;
    
    pthread_create(&thread_id, NULL, thread_function, &thread_arg);
    pthread_join(thread_id, NULL);
    
    printf("Thread return value: %d\n", thread_arg);
    
    return 0;
}

在上面的例子中,thread_function函数将会将thread_arg的值设置为10,并且通过返回NULL来结束线程。在main函数中,我们创建了一个线程,并且等待该线程结束。线程结束后,我们将线程的返回值打印出来。在这个例子中,线程返回值为10。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c语言如何获取shell返回值

0