pthread_create ()-创建线程
标准
标准/扩展 | C 或 C++ | 依赖关系 |
---|---|---|
POSIX.4a
单一 UNIX 规范版本 3 |
两个 | POSIX(ON)
|
格式
#define _OPEN_THREADS
#include <pthread.h>
int pthread_create(pthread_t *thread, pthread_attr_t *attr,
void *(*start_routine) (void *arg), void *arg);
SUSV3
#define _UNIX03_THREADS
#include <pthread.h>
int pthread_create(pthread_t * __restrict__thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *arg),
void * __restrict__arg);
一般描述
使用由 pthread_attr_init () 创建的线程属性对象 attr定义的属性在进程中创建新线程。
如果 attr 为 NULL ,那么将使用缺省属性。 请参阅 pthread_attr_init ()-初始化线程属性对象 以获取线程属性及其缺省值的描述。 如果稍后更改 attr 指定的属性,那么线程的属性不受影响。
pthread_t 是用于唯一标识线程的数据类型。 它由 pthread_create () 返回,并由需要线程标识的函数调用中的应用程序使用。
将创建运行 start_routine的线程,并使用 arg 作为唯一参数。 如果 pthread_create () 成功完成,那么 thread 将包含创建的线程的标识。 如果失败,那么不会创建新线程,并且未定义 线程 所引用的位置的内容。
进程中线程限制的系统缺省值由 BPXPRMxx parmlib 成员中的 MAXTHREADS 设置。
最大线程数取决于 16M以下的专用区域的大小。 pthread_create () 在创建新线程之前检查此地址空间。 实际限制为 200 到 400 个线程。
C++的特殊行为: 由于 C 和 C++ 链接约定不兼容,因此 pthread_create () 无法接收 C++ 函数指针作为启动例程函数指针。如果尝试将 C++ 函数指针传递给 pthread_create () ,那么编译器会将其标记为错误。 您可以通过将 C 或 C++ 函数声明为 extern "C" 来将其传递到 pthread_create ()。
启动的线程提供了与 try-throw-catch 处理作用域有关的边界。 在启动例程中执行的抛出或由启动例程调用的函数会导致堆栈对启动例程 (或直到捕获到) 进行解绕并包括该启动例程。 堆栈放线不会超出启动例程返回到线程创建程序中。 如果未捕获到异常,那么将调用 terminate ()。
异常堆栈 (用于 try-throw-catch) 基于线程。 除非未捕获条件,否则由线程抛出条件或由线程重新抛出条件不会影响另一个线程上的异常处理。
返回值
如果成功, pthread_create () 将返回 0。
- 错误代码
- 描述
- 再次
- 系统缺少创建另一个线程所需的资源。
- EINVAL
- thread 指定的值为空。
- ELEMULTITHREADFORK
- 从通过从多线程进程调用 fork () 创建的子进程调用了 pthread_create ()。 此子进程被限制为多线程。
- ENOMEM
- 没有足够的内存来创建线程。
单一 UNIX 规范版本的特殊行为 3: 如果失败, pthread_create () 将返回错误号以指示错误。
示例
/* CELEBP27 */
#define _OPEN_THREADS
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
void *thread(void *arg) {
char *ret;
printf("thread() entered with argument '%s'\n", arg);
if ((ret = (char*) malloc(20)) == NULL) {
perror("malloc() error");
exit(2);
}
strcpy(ret, "This is a test");
pthread_exit(ret);
}
main() {
pthread_t thid;
void *ret;
if (pthread_create(&thid, NULL, thread, "thread 1") != 0) {
perror("pthread_create() error");
exit(1);
}
if (pthread_join(thid, &ret) != 0) {
perror("pthread_create() error");
exit(3);
}
printf("thread exited with '%s'\n", ret);
}
thread() entered with argument 'thread 1'
thread exited with 'This is a test'