溫馨提示×

C語言怎么獲取線程返回值

小億
240
2023-11-29 19:39:22
欄目: 編程語言

在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。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女