多线程编程指南

创建缺省线程

如果未指定属性对象,则该对象为 NULL,系统会创建具有以下属性的缺省线程:

还可以用 pthread_attr_init() 创建缺省属性对象,然后使用该属性对象来创建缺省线程。有关详细信息,请参见初始化属性一节。

pthread_create 语法

使用 pthread_create(3C) 可以向当前进程中添加新的受控线程。

int	pthread_create(pthread_t *tid, const pthread_attr_t *tattr,

    void*(*start_routine)(void *), void *arg);
#include <pthread.h>



pthread_attr_t() tattr;

pthread_t tid;

extern void *start_routine(void *arg);

void *arg;

int ret; 



/* default behavior*/

ret = pthread_create(&tid, NULL, start_routine, arg);



/* initialized with default attributes */

ret = pthread_attr_init(&tattr);

/* default behavior specified*/

ret = pthread_create(&tid, &tattr, start_routine, arg);

使用具有必要状态行为的 attr 调用 pthread_create() 函数。 start_routine 是新线程最先执行的函数。当 start_routine 返回时,该线程将退出,其退出状态设置为由 start_routine 返回的值。请参见pthread_create 语法

pthread_create() 成功时,所创建线程的 ID 被存储在由 tid 指向的位置中。

使用 NULL 属性参数或缺省属性调用 pthread_create() 时,pthread_create() 会创建一个缺省线程。在对 tattr 进行初始化之后,该线程将获得缺省行为。

pthread_create 返回值

pthread_create() 在调用成功完成之后返回零。其他任何返回值都表示出现了错误。如果检测到以下任一情况,pthread_create() 将失败并返回相应的值。


EAGAIN

描述:

超出了系统限制,如创建的线程太多。


EINVAL

描述:

tattr 的值无效。