Changes: Ready for 5.13
[man-pages.git] / man3 / pthread_create.3
blob2d44583d2ddd927761ccc251f3a11e8f546b96ff
1 .\" Copyright (c) 2008 Linux Foundation, written by Michael Kerrisk
2 .\"     <mtk.manpages@gmail.com>
3 .\"
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
8 .\"
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
13 .\"
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein.  The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
26 .TH PTHREAD_CREATE 3 2021-03-22 "Linux" "Linux Programmer's Manual"
27 .SH NAME
28 pthread_create \- create a new thread
29 .SH SYNOPSIS
30 .nf
31 .B #include <pthread.h>
32 .PP
33 .BI "int pthread_create(pthread_t *restrict " thread ,
34 .BI "                   const pthread_attr_t *restrict " attr ,
35 .BI "                   void *(*" start_routine ")(void *),"
36 .BI "                   void *restrict " arg );
37 .fi
38 .PP
39 Compile and link with \fI\-pthread\fP.
40 .SH DESCRIPTION
41 The
42 .BR pthread_create ()
43 function starts a new thread in the calling process.
44 The new thread starts execution by invoking
45 .IR start_routine ();
46 .IR arg
47 is passed as the sole argument of
48 .IR start_routine ().
49 .PP
50 The new thread terminates in one of the following ways:
51 .IP * 2
52 It calls
53 .BR pthread_exit (3),
54 specifying an exit status value that is available to another thread
55 in the same process that calls
56 .BR pthread_join (3).
57 .IP *
58 It returns from
59 .IR start_routine ().
60 This is equivalent to calling
61 .BR pthread_exit (3)
62 with the value supplied in the
63 .I return
64 statement.
65 .IP *
66 It is canceled (see
67 .BR pthread_cancel (3)).
68 .IP *
69 Any of the threads in the process calls
70 .BR exit (3),
71 or the main thread performs a return from
72 .IR main ().
73 This causes the termination of all threads in the process.
74 .PP
75 The
76 .I attr
77 argument points to a
78 .I pthread_attr_t
79 structure whose contents are used at thread creation time to
80 determine attributes for the new thread;
81 this structure is initialized using
82 .BR pthread_attr_init (3)
83 and related functions.
85 .I attr
86 is NULL,
87 then the thread is created with default attributes.
88 .PP
89 Before returning, a successful call to
90 .BR pthread_create ()
91 stores the ID of the new thread in the buffer pointed to by
92 .IR thread ;
93 this identifier is used to refer to the thread
94 in subsequent calls to other pthreads functions.
95 .PP
96 The new thread inherits a copy of the creating thread's signal mask
97 .RB ( pthread_sigmask (3)).
98 The set of pending signals for the new thread is empty
99 .RB ( sigpending (2)).
100 The new thread does not inherit the creating thread's
101 alternate signal stack
102 .RB ( sigaltstack (2)).
104 The new thread inherits the calling thread's floating-point environment
105 .RB ( fenv (3)).
107 The initial value of the new thread's CPU-time clock is 0
108 (see
109 .BR pthread_getcpuclockid (3)).
110 .\" CLOCK_THREAD_CPUTIME_ID in clock_gettime(2)
111 .SS Linux-specific details
112 The new thread inherits copies of the calling thread's capability sets
113 (see
114 .BR capabilities (7))
115 and CPU affinity mask (see
116 .BR sched_setaffinity (2)).
117 .SH RETURN VALUE
118 On success,
119 .BR pthread_create ()
120 returns 0;
121 on error, it returns an error number, and the contents of
122 .IR *thread
123 are undefined.
124 .SH ERRORS
126 .B EAGAIN
127 Insufficient resources to create another thread.
129 .B EAGAIN
130 .\" NOTE! The following should match the description in fork(2)
131 A system-imposed limit on the number of threads was encountered.
132 There are a number of limits that may trigger this error: the
133 .BR RLIMIT_NPROC
134 soft resource limit (set via
135 .BR setrlimit (2)),
136 which limits the number of processes and threads for a real user ID,
137 was reached;
138 the kernel's system-wide limit on the number of processes and threads,
139 .IR /proc/sys/kernel/threads\-max ,
140 was reached (see
141 .BR proc (5));
142 or the maximum number of PIDs,
143 .IR /proc/sys/kernel/pid_max ,
144 was reached (see
145 .BR proc (5)).
147 .B EINVAL
148 Invalid settings in
149 .IR attr .
151 .\" FIXME . Test the following
152 .B EPERM
153 No permission to set the scheduling policy and parameters specified in
154 .IR attr .
155 .SH ATTRIBUTES
156 For an explanation of the terms used in this section, see
157 .BR attributes (7).
158 .ad l
161 allbox;
162 lbx lb lb
163 l l l.
164 Interface       Attribute       Value
166 .BR pthread_create ()
167 T}      Thread safety   MT-Safe
171 .sp 1
172 .SH CONFORMING TO
173 POSIX.1-2001, POSIX.1-2008.
174 .SH NOTES
176 .BR pthread_self (3)
177 for further information on the thread ID returned in
178 .IR *thread
180 .BR pthread_create ().
181 Unless real-time scheduling policies are being employed,
182 after a call to
183 .BR pthread_create (),
184 it is indeterminate which thread\(emthe caller or the new thread\(emwill
185 next execute.
187 A thread may either be
188 .I joinable
190 .IR detached .
191 If a thread is joinable, then another thread can call
192 .BR pthread_join (3)
193 to wait for the thread to terminate and fetch its exit status.
194 Only when a terminated joinable thread has been joined are
195 the last of its resources released back to the system.
196 When a detached thread terminates,
197 its resources are automatically released back to the system:
198 it is not possible to join with the thread in order to obtain
199 its exit status.
200 Making a thread detached is useful for some types of daemon threads
201 whose exit status the application does not need to care about.
202 By default, a new thread is created in a joinable state, unless
203 .I attr
204 was set to create the thread in a detached state (using
205 .BR pthread_attr_setdetachstate (3)).
207 Under the NPTL threading implementation, if the
208 .BR RLIMIT_STACK
209 soft resource limit
210 .IR "at the time the program started"
211 has any value other than "unlimited",
212 then it determines the default stack size of new threads.
213 Using
214 .BR pthread_attr_setstacksize (3),
215 the stack size attribute can be explicitly set in the
216 .I attr
217 argument used to create a thread,
218 in order to obtain a stack size other than the default.
219 If the
220 .BR RLIMIT_STACK
221 resource limit is set to "unlimited",
222 a per-architecture value is used for the stack size.
223 Here is the value for a few architectures:
226 allbox;
227 lb lb
228 l r.
229 Architecture    Default stack size
230 i386    2 MB
231 IA-64   32 MB
232 PowerPC 4 MB
233 S/390   2 MB
234 Sparc-32        2 MB
235 Sparc-64        4 MB
236 x86_64  2 MB
239 .SH BUGS
240 In the obsolete LinuxThreads implementation,
241 each of the threads in a process has a different process ID.
242 This is in violation of the POSIX threads specification,
243 and is the source of many other nonconformances to the standard; see
244 .BR pthreads (7).
245 .SH EXAMPLES
246 The program below demonstrates the use of
247 .BR pthread_create (),
248 as well as a number of other functions in the pthreads API.
250 In the following run,
251 on a system providing the NPTL threading implementation,
252 the stack size defaults to the value given by the
253 "stack size" resource limit:
255 .in +4n
257 .RB "$" " ulimit \-s"
258 8192            # The stack size limit is 8 MB (0x800000 bytes)
259 .RB "$" " ./a.out hola salut servus"
260 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
261 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
262 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
263 Joined with thread 1; returned value was HOLA
264 Joined with thread 2; returned value was SALUT
265 Joined with thread 3; returned value was SERVUS
269 In the next run, the program explicitly sets a stack size of 1\ MB (using
270 .BR pthread_attr_setstacksize (3))
271 for the created threads:
273 .in +4n
275 .RB "$" " ./a.out \-s 0x100000 hola salut servus"
276 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
277 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
278 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
279 Joined with thread 1; returned value was HOLA
280 Joined with thread 2; returned value was SALUT
281 Joined with thread 3; returned value was SERVUS
284 .SS Program source
287 #include <pthread.h>
288 #include <string.h>
289 #include <stdio.h>
290 #include <stdlib.h>
291 #include <unistd.h>
292 #include <errno.h>
293 #include <ctype.h>
295 #define handle_error_en(en, msg) \e
296         do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
298 #define handle_error(msg) \e
299         do { perror(msg); exit(EXIT_FAILURE); } while (0)
301 struct thread_info {    /* Used as argument to thread_start() */
302     pthread_t thread_id;        /* ID returned by pthread_create() */
303     int       thread_num;       /* Application\-defined thread # */
304     char     *argv_string;      /* From command\-line argument */
307 /* Thread start function: display address near top of our stack,
308    and return upper\-cased copy of argv_string. */
310 static void *
311 thread_start(void *arg)
313     struct thread_info *tinfo = arg;
314     char *uargv;
316     printf("Thread %d: top of stack near %p; argv_string=%s\en",
317             tinfo\->thread_num, (void *) &tinfo, tinfo\->argv_string);
319     uargv = strdup(tinfo\->argv_string);
320     if (uargv == NULL)
321         handle_error("strdup");
323     for (char *p = uargv; *p != \(aq\e0\(aq; p++)
324         *p = toupper(*p);
326     return uargv;
330 main(int argc, char *argv[])
332     int s, opt, num_threads;
333     pthread_attr_t attr;
334     ssize_t stack_size;
335     void *res;
337     /* The "\-s" option specifies a stack size for our threads. */
339     stack_size = \-1;
340     while ((opt = getopt(argc, argv, "s:")) != \-1) {
341         switch (opt) {
342         case \(aqs\(aq:
343             stack_size = strtoul(optarg, NULL, 0);
344             break;
346         default:
347             fprintf(stderr, "Usage: %s [\-s stack\-size] arg...\en",
348                     argv[0]);
349             exit(EXIT_FAILURE);
350         }
351     }
353     num_threads = argc \- optind;
355     /* Initialize thread creation attributes. */
357     s = pthread_attr_init(&attr);
358     if (s != 0)
359         handle_error_en(s, "pthread_attr_init");
361     if (stack_size > 0) {
362         s = pthread_attr_setstacksize(&attr, stack_size);
363         if (s != 0)
364             handle_error_en(s, "pthread_attr_setstacksize");
365     }
367     /* Allocate memory for pthread_create() arguments. */
369     struct thread_info *tinfo = calloc(num_threads, sizeof(*tinfo));
370     if (tinfo == NULL)
371         handle_error("calloc");
373     /* Create one thread for each command\-line argument. */
375     for (int tnum = 0; tnum < num_threads; tnum++) {
376         tinfo[tnum].thread_num = tnum + 1;
377         tinfo[tnum].argv_string = argv[optind + tnum];
379         /* The pthread_create() call stores the thread ID into
380            corresponding element of tinfo[]. */
382         s = pthread_create(&tinfo[tnum].thread_id, &attr,
383                            &thread_start, &tinfo[tnum]);
384         if (s != 0)
385             handle_error_en(s, "pthread_create");
386     }
388     /* Destroy the thread attributes object, since it is no
389        longer needed. */
391     s = pthread_attr_destroy(&attr);
392     if (s != 0)
393         handle_error_en(s, "pthread_attr_destroy");
395     /* Now join with each thread, and display its returned value. */
397     for (int tnum = 0; tnum < num_threads; tnum++) {
398         s = pthread_join(tinfo[tnum].thread_id, &res);
399         if (s != 0)
400             handle_error_en(s, "pthread_join");
402         printf("Joined with thread %d; returned value was %s\en",
403                 tinfo[tnum].thread_num, (char *) res);
404         free(res);      /* Free memory allocated by thread */
405     }
407     free(tinfo);
408     exit(EXIT_SUCCESS);
411 .SH SEE ALSO
412 .ad l
414 .BR getrlimit (2),
415 .BR pthread_attr_init (3),
416 .BR pthread_cancel (3),
417 .BR pthread_detach (3),
418 .BR pthread_equal (3),
419 .BR pthread_exit (3),
420 .BR pthread_getattr_np (3),
421 .BR pthread_join (3),
422 .BR pthread_self (3),
423 .BR pthread_setattr_default_np (3),
424 .BR pthreads (7)