PTHREAD_CREATE(3) Linux Programmer's Manual PTHREAD_CREATE(3)
NAME
pthread_create - create a new thread
SYNOPSIS
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
Compile and link with -pthread. //编译和链接时需要加 -pthread
DESCRIPTION
The pthread_create() function starts a new thread in the calling process. The new thread starts execution by invoking start_routine(); arg is passed as the sole argument of start_routine().
/*pthread_create() 函数在调用进程中启动一个新线程。新线程通过调用 start_routine() 开始执行; arg 作为 start_routine() 的唯一参数传递。*/
The new thread terminates in one of the following ways:
* It calls pthread_exit(3), specifying an exit status value that is available to another thread in the same process that calls pthread_join(3).
* It returns from start_routine(). This is equivalent to calling pthread_exit(3) with the value supplied in the return statement.
* It is canceled (see pthread_cancel(3)).
* Any of the threads in the process calls exit(3), or the main thread performs a return from main(). This causes the termination of all threads in the process.
/*新线程以下列方式之一终止:
*调用 pthread_exit(3) 函数来指定一个退出状态值,可以在同一进程的其他线程中调用 pthread_join(3) 函数来获得这个状态值。
*从 start_routine() 函数中返回:这相当于调用 pthread_exit(3),并且返回值由 return 声明提供。
*它被取消(参见 pthread_cancel(3))。
*进程中的任何线程调用了 exit(3),或者主线程的 main() 函数中执行了 return。 这会导致进程中所有线程都终止。*/
The attr argument points to a pthread_attr_t structure whose contents are used at thread creation time to determine attributes for the new thread; this structure is initialized using pthread_attr_init(3) and related functions. If attr is NULL, then the thread is created with default attributes.
/*attr 参数指向 pthread_attr_t 结构,其内容在创建线程时用于确定新线程的属性; 使用 pthread_attr_init(3) 和相关函数初始化此结构。 如果 attr 为 NULL,则使用默认属性创建线程。*/
Before returning, a successful call to pthread_create() stores the ID of the new thread in the buffer pointed to by thread; this identifier is used to refer to the thread in subsequent calls to other pthreads functions.
/*在返回之前,成功调用 pthread_create() 会将新线程的 ID 存储在线程指向的缓冲区中; 此标识符用于在后续调用其他线程函数时引用该线程。*/
The new thread inherits a copy of the creating thread's signal mask (pthread_sigmask(3)). The set of pending signals for the new thread is empty (sigpending(2)). The new thread does not inherit the creating thread's alternate signal stack (sigaltstack(2)).
/*新线程继承创建线程的信号掩码的副本 (pthread_sigmask(3))。新线程的待处理信号集为空 (sigpending(2))。新线程不继承创建线程的备用信号堆栈 (sigaltstack(2))。*/
The new thread inherits the calling thread's floating-point environment (fenv(3)).
/*新线程继承调用线程的浮点环境(fenv(3))*/
The initial value of the new thread's CPU-time clock is 0 (see pthread_getcpuclockid(3)).
/*新线程的 CPU 时间时钟的初始值为 0 (参见 pthread_getcpuclockid(3))*/
Linux-specific details //Linux 系统特有的细节
The new thread inherits copies of the calling thread's capability sets (see capabilities(7)) and CPU affinity mask (see sched_setaffinity(2)).
/*新线程继承调用线程的功能集(请参阅 capabilities(7)) 和 CPU 亲和力掩码(请参阅 sched_setaffinity(2)) 的副本。*/
RETURN VALUE
On success, pthread_create() returns 0; on error, it returns an error number, and the contents of *thread are undefined.
/*成功时,pthread_create() 返回 0; 如果出错,则返回错误编号,并且 thread 为野指针。*/
ERRORS
EAGAIN Insufficient resources to create another thread, or a system-imposed limit on the number of threads was encountered. The latter case may occur in two ways: the RLIMIT_NPROC soft resource limit (set via setrlimit(2)), which limits the number of process for a real user ID, was reached; or the kernel's system-wide limit on the number of threads, /proc/sys/kernel/threads-max, was reached.
/*EAGAIN 资源不足以创建另一个线程,或达到系统线程数的上限。 后一种情况可能以两种方式发生:达到 RLIMIT_NPROC 软资源上限(通过 setrlimit(2) 设置),它限制了真实用户 ID 的进程数量; 或者达到内核对线程数的系统范围限制,/proc/sys/kernel/threads-max。*/
EINVAL Invalid settings in attr.
/*EINVAL attr 的无效设置。*/
EPERM No permission to set the scheduling policy and parameters specified in attr.
/*EPERM 无权设置 attr 中指定的调度策略和参数*/
CONFORMING TO
POSIX.1-2001.
NOTES
See pthread_self(3) for further information on the thread ID returned in *thread by pthread_create(). Unless real-time scheduling policies are being employed, after a call to pthread_create(), it is indeterminate which thread—the caller or the new thread—will next execute.
/*有关 pthread_create() 在 *thread 中返回的线程 ID 的更多信息,请参阅 pthread_self(3)。 除非采用实时调度策略,否则在调用 pthread_create() 之后,接下来要执行的调用者或新线程的线程是不确定的。*/
A thread may either be joinable or detached. If a thread is joinable, then another thread can call pthread_join(3) to wait for the thread to terminate and fetch its exit status. Only when a terminated joinable thread has been joined are the last of its resources released back to the system. When a detached thread terminates, its resources are automatically released back to the system: it is not possible to join with the thread in order to obtain its exit status. Making a thread detached is useful for some types of daemon threads whose exit status the application does not need to care about. By default, a new thread is created in a joinable state, unless attr was set to create the thread in a detached state (using pthread_attr_setdetachstate(3)).
/*线程可以是可连接的也可以是分离的。如果一个线程是可连接的,那么另一个线程可以调用 pthread_join(3) 来等待线程终止并获取其退出状态。仅当终止的线程是已连接的最后一个线程时时,资源才会释放回系统。当分离的线程终止时,其资源会自动释放回系统:这种线程是无法获取其退出状态的。 使线程分离对某些类型的守护线程很有用,这些守护线程的退出状态是应用程序不需要关心的。 默认情况下,在可连接状态下创建新线程,除非将 attr 设置为以分离状态创建线程(使用 pthread_attr_setdetachstate(3))。*/
On Linux/x86-32, the default stack size for a new thread is 2 megabytes. Under the NPTL threading implementation, if the RLIMIT_STACK soft resource limit at the time the program started has any value other than "unlimited", then it determines the default stack size of new threads. Using pthread_attr_setstacksize(3), the stack size attribute can be explicitly set in the attr argument used to create a thread, in order to obtain a stack size other than the default.
/*在 Linux/x86-32 上,新线程的默认堆栈大小为 2M 字节。 在 NPTL 线程实现下,如果程序启动时的 RLIMIT_STACK 软资源限制具有"无限制"以外的任何值,则它确定新线程的默认堆栈大小。 使用 pthread_attr_setstacksize(3),可以在用于创建线程的 attr 参数中显式设置堆栈大小属性,以获得非默认堆栈大小。*/
EXAMPLE
The program below demonstrates the use of pthread_create(), as well as a number of other functions in the pthreads API.
/*下面的程序演示了 pthread_create() 的使用,以及 pthreads API 中的许多其他函数。*/
In the following run, on a system providing the NPTL threading implementation, the stack size defaults to the value given by the "stack size" resource limit:
/*在下面的运行中,在提供 NPTL 线程实现的系统上,堆栈大小默认为"堆栈大小"资源限制给出的值:*/
$ ulimit -s
8192 # The stack size limit is 8 MB (0x80000 bytes)
$ ./a.out hola salut servus
Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
Joined with thread 1; returned value was HOLA
Joined with thread 2; returned value was SALUT
Joined with thread 3; returned value was SERVUS
In the next run, the program explicitly sets a stack size of 1MB (using pthread_attr_setstacksize(3)) for the created threads:
$ ./a.out -s 0x100000 hola salut servus
Thread 1: top of stack near 0xb7d723b8; argv_string=hola
Thread 2: top of stack near 0xb7c713b8; argv_string=salut
Thread 3: top of stack near 0xb7b703b8; argv_string=servus
Joined with thread 1; returned value was HOLA
Joined with thread 2; returned value was SALUT
Joined with thread 3; returned value was SERVUS
Program source
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id; /* ID returned by pthread_create() */
int thread_num; /* Application-defined thread # */
char *argv_string; /* From command-line argument */
};
/* Thread start function: display address near top of our stack,
and return upper-cased copy of argv_string */
static void *
thread_start(void *arg)
{
struct thread_info *tinfo = (struct thread_info *) arg;
char *uargv, *p;
printf("Thread %d: top of stack near %p; argv_string=%s\n",
tinfo->thread_num, &p, tinfo->argv_string);
uargv = strdup(tinfo->argv_string);
if (uargv == NULL)
handle_error("strdup");
for (p = uargv; *p != '\0'; p++)
*p = toupper(*p);
return uargv;
}
int
main(int argc, char *argv[])
{
int s, tnum, opt, num_threads;
struct thread_info *tinfo;
pthread_attr_t attr;
int stack_size;
void *res;
/* The "-s" option specifies a stack size for our threads */
stack_size = -1;
while ((opt = getopt(argc, argv, "s:")) != -1) {
switch (opt) {
case 's':
stack_size = strtoul(optarg, NULL, 0);
break;
default:
fprintf(stderr, "Usage: %s [-s stack-size] arg...\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
num_threads = argc - optind;
/* Initialize thread creation attributes */
s = pthread_attr_init(&attr);
if (s != 0)
handle_error_en(s, "pthread_attr_init");
if (stack_size > 0) {
s = pthread_attr_setstacksize(&attr, stack_size);
if (s != 0)
handle_error_en(s, "pthread_attr_setstacksize");
}
/* Allocate memory for pthread_create() arguments */
tinfo = calloc(num_threads, sizeof(struct thread_info));
if (tinfo == NULL)
handle_error("calloc");
/* Create one thread for each command-line argument */
for (tnum = 0; tnum < num_threads; tnum++) {
tinfo[tnum].thread_num = tnum + 1;
tinfo[tnum].argv_string = argv[optind + tnum];
/* The pthread_create() call stores the thread ID into
corresponding element of tinfo[] */
s = pthread_create(&tinfo[tnum].thread_id, &attr,
&thread_start, &tinfo[tnum]);
if (s != 0)
handle_error_en(s, "pthread_create");
}
/* Destroy the thread attributes object, since it is no
longer needed */
s = pthread_attr_destroy(&attr);
if (s != 0)
handle_error_en(s, "pthread_attr_destroy");
/* Now join with each thread, and display its returned value */
for (tnum = 0; tnum < num_threads; tnum++) {
s = pthread_join(tinfo[tnum].thread_id, &res);
if (s != 0)
handle_error_en(s, "pthread_join");
printf("Joined with thread %d; returned value was %s\n",
tinfo[tnum].thread_num, (char *) res);
free(res); /* Free memory allocated by thread */
}
free(tinfo);
exit(EXIT_SUCCESS);
}
BUGS
In the obsolete LinuxThreads implementation, each of the threads in a process has a different process ID. This is in violation of the POSIX threads specification, and is the source of many other nonconformances to the standard; see pthreads(7).
/*在过时的 LinuxThreads 实现中,进程中的每个线程都有不同的进程 ID。 这违反了 POSIX 线程规范,并且是该标准的许多其他不符合项的来源; 见 pthreads(7)。*/
SEE ALSO
getrlimit(2), pthread_attr_init(3), pthread_cancel(3), pthread_detach(3), pthread_equal(3), pthread_exit(3), pthread_getattr_np(3), pthread_join(3), pthread_self(3), pthreads(7)
COLOPHON
This page is part of release 3.35 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at http://man7.org/linux/man-pages/.
Linux 2008-11-11 PTHREAD_CREATE(3)
pthread_create 函数 man 手册翻译
最新推荐文章于 2024-06-28 16:16:29 发布