当前位置: C语言 -- 标准库 -- <threads.h> -- thrd_join

thrd_join函数


概要:
#include <threads.h>
int thrd_join(thrd_t thr, int *res);

描述:

该函数将参数thr标识的线程与当前线程连接,当前线程会被阻塞,直至参数thr标识的线程终止执行。如果参数res不是空指针,函数将参数thr标识线程的结果代码存储在参数res指向的整数中。thrd_join函数的完成与参数thr标识线程的终止是同步的。调用该函数前,参数thr标识的线程应没有被分离或者和其它线程连接。


参数:
thrd_t thr

连接线程的标识符。

int *res

指向int类型对象的指针。


返回值:

如果连接成功,函数返回thrd_success;如果连接不成功,函数返回thrd_error


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
/*函数thrd_join范例*/

#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif

#include <stdio.h>
#include <stdlib.h>
#include <threads.h>

/*新线程中执行的函数。*/
int func(void *arg)
{
    puts((char *)arg);
    
    thrd_exit(0);
}

int main(void)
{
    thrd_t threadId;
    char arr[] = "This is a new thread.";
    
    /*创建线程。*/
    if(thrd_create(&threadId, func, arr) != thrd_success)
    {
        perror("thrd_create error");
        exit(EXIT_FAILURE);
    }

    /*连接线程。*/
    if(thrd_join(threadId, NULL) == thrd_success)
        puts("The new thread has been successfully joined.");
    else
        perror("thrd_join error");
    
    return 0;
}


输出:

This is a new thread.

The new thread has been successfully joined.

注:使用Pelles C编译。


相关内容:
thrd_current 标识调用线程的函数。
thrd_detach 分离线程的函数。
thrd_equal 测试两个线程是否为同一线程的函数。
thrd_exit 终止当前线程的函数。
thrd_sleep 暂停当前线程的函数。
thrd_create 创建线程的函数。
thrd_yield 让其它线程运行的函数。