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

thrd_create函数


概要:
#include <threads.h>
int thrd_create(thrd_t *thr, thrd_start_t func, void *arg);

描述:

该函数创建一个执行func(arg)的新线程。如果新线程创建成功,函数将参数thr指向的对象设置为新线程的标识符。一旦原线程退出,并且原线程被分离或者连接到另一个线程,线程的标识符可以重新用于不同的线程。thrd_create函数创建新线程的完成与新线程的开始执行是同步的。

func返回与使用func返回值调用thrd_exit函数具有相同的行为。


参数:
thrd_t *thr

指向新线程标识符的指针。

thrd_start_t func

指向新线程中执行函数的指针。

void *arg

指向传递给func函数参数的指针。


返回值:

如果成功创建新线程,函数返回thrd_success;如果不能分配新线程请求的内存,函数返回thrd_nomem;如果无法创建新线程,函数返回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 
40 
41 
42 
43 
/*函数thrd_create范例*/

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

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

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

int main(void)
{
    thrd_t threadId;
    char arr[] = "This is a new thread.";
    
    /*创建新线程。*/
    switch(thrd_create(&threadId, func, arr))
    {
    case thrd_nomem:
        perror("thrd_nomem");
        exit(EXIT_FAILURE);
    case thrd_error:
        perror("thrd_error");
        exit(EXIT_FAILURE);
    default:
        puts("The new thread has been created successfully.");
        break;
    }

    /*连接线程。*/
    thrd_join(threadId, NULL);
    
    return 0;
}


输出:

The new thread has been created successfully.

This is a new thread.

注:使用Pelles C编译。


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