]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man3/pthread_create.3
Various pages: Inside code blocks (.EX/.EE) use \- to get real minus signs
[thirdparty/man-pages.git] / man3 / pthread_create.3
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 2020-11-01 "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 *" thread ", const pthread_attr_t *" attr ,
34 .BI " void *(*" start_routine ")(void *), void *" arg );
35 .fi
36 .PP
37 Compile and link with \fI\-pthread\fP.
38 .SH DESCRIPTION
39 The
40 .BR pthread_create ()
41 function starts a new thread in the calling process.
42 The new thread starts execution by invoking
43 .IR start_routine ();
44 .IR arg
45 is passed as the sole argument of
46 .IR start_routine ().
47 .PP
48 The new thread terminates in one of the following ways:
49 .IP * 2
50 It calls
51 .BR pthread_exit (3),
52 specifying an exit status value that is available to another thread
53 in the same process that calls
54 .BR pthread_join (3).
55 .IP *
56 It returns from
57 .IR start_routine ().
58 This is equivalent to calling
59 .BR pthread_exit (3)
60 with the value supplied in the
61 .I return
62 statement.
63 .IP *
64 It is canceled (see
65 .BR pthread_cancel (3)).
66 .IP *
67 Any of the threads in the process calls
68 .BR exit (3),
69 or the main thread performs a return from
70 .IR main ().
71 This causes the termination of all threads in the process.
72 .PP
73 The
74 .I attr
75 argument points to a
76 .I pthread_attr_t
77 structure whose contents are used at thread creation time to
78 determine attributes for the new thread;
79 this structure is initialized using
80 .BR pthread_attr_init (3)
81 and related functions.
82 If
83 .I attr
84 is NULL,
85 then the thread is created with default attributes.
86 .PP
87 Before returning, a successful call to
88 .BR pthread_create ()
89 stores the ID of the new thread in the buffer pointed to by
90 .IR thread ;
91 this identifier is used to refer to the thread
92 in subsequent calls to other pthreads functions.
93 .PP
94 The new thread inherits a copy of the creating thread's signal mask
95 .RB ( pthread_sigmask (3)).
96 The set of pending signals for the new thread is empty
97 .RB ( sigpending (2)).
98 The new thread does not inherit the creating thread's
99 alternate signal stack
100 .RB ( sigaltstack (2)).
101 .PP
102 The new thread inherits the calling thread's floating-point environment
103 .RB ( fenv (3)).
104 .PP
105 The initial value of the new thread's CPU-time clock is 0
106 (see
107 .BR pthread_getcpuclockid (3)).
108 .\" CLOCK_THREAD_CPUTIME_ID in clock_gettime(2)
109 .SS Linux-specific details
110 The new thread inherits copies of the calling thread's capability sets
111 (see
112 .BR capabilities (7))
113 and CPU affinity mask (see
114 .BR sched_setaffinity (2)).
115 .SH RETURN VALUE
116 On success,
117 .BR pthread_create ()
118 returns 0;
119 on error, it returns an error number, and the contents of
120 .IR *thread
121 are undefined.
122 .SH ERRORS
123 .TP
124 .B EAGAIN
125 Insufficient resources to create another thread.
126 .TP
127 .B EAGAIN
128 .\" NOTE! The following should match the description in fork(2)
129 A system-imposed limit on the number of threads was encountered.
130 There are a number of limits that may trigger this error: the
131 .BR RLIMIT_NPROC
132 soft resource limit (set via
133 .BR setrlimit (2)),
134 which limits the number of processes and threads for a real user ID,
135 was reached;
136 the kernel's system-wide limit on the number of processes and threads,
137 .IR /proc/sys/kernel/threads-max ,
138 was reached (see
139 .BR proc (5));
140 or the maximum number of PIDs,
141 .IR /proc/sys/kernel/pid_max ,
142 was reached (see
143 .BR proc (5)).
144 .TP
145 .B EINVAL
146 Invalid settings in
147 .IR attr .
148 .TP
149 .\" FIXME . Test the following
150 .B EPERM
151 No permission to set the scheduling policy and parameters specified in
152 .IR attr .
153 .SH ATTRIBUTES
154 For an explanation of the terms used in this section, see
155 .BR attributes (7).
156 .ad l
157 .nh
158 .TS
159 allbox;
160 lbx lb lb
161 l l l.
162 Interface Attribute Value
163 T{
164 .BR pthread_create ()
165 T} Thread safety MT-Safe
166 .TE
167 .hy
168 .ad
169 .sp 1
170 .SH CONFORMING TO
171 POSIX.1-2001, POSIX.1-2008.
172 .SH NOTES
173 See
174 .BR pthread_self (3)
175 for further information on the thread ID returned in
176 .IR *thread
177 by
178 .BR pthread_create ().
179 Unless real-time scheduling policies are being employed,
180 after a call to
181 .BR pthread_create (),
182 it is indeterminate which thread\(emthe caller or the new thread\(emwill
183 next execute.
184 .PP
185 A thread may either be
186 .I joinable
187 or
188 .IR detached .
189 If a thread is joinable, then another thread can call
190 .BR pthread_join (3)
191 to wait for the thread to terminate and fetch its exit status.
192 Only when a terminated joinable thread has been joined are
193 the last of its resources released back to the system.
194 When a detached thread terminates,
195 its resources are automatically released back to the system:
196 it is not possible to join with the thread in order to obtain
197 its exit status.
198 Making a thread detached is useful for some types of daemon threads
199 whose exit status the application does not need to care about.
200 By default, a new thread is created in a joinable state, unless
201 .I attr
202 was set to create the thread in a detached state (using
203 .BR pthread_attr_setdetachstate (3)).
204 .PP
205 Under the NPTL threading implementation, if the
206 .BR RLIMIT_STACK
207 soft resource limit
208 .IR "at the time the program started"
209 has any value other than "unlimited",
210 then it determines the default stack size of new threads.
211 Using
212 .BR pthread_attr_setstacksize (3),
213 the stack size attribute can be explicitly set in the
214 .I attr
215 argument used to create a thread,
216 in order to obtain a stack size other than the default.
217 If the
218 .BR RLIMIT_STACK
219 resource limit is set to "unlimited",
220 a per-architecture value is used for the stack size.
221 Here is the value for a few architectures:
222 .RS
223 .TS
224 allbox;
225 lb lb
226 l r.
227 Architecture Default stack size
228 i386 2 MB
229 IA-64 32 MB
230 PowerPC 4 MB
231 S/390 2 MB
232 Sparc-32 2 MB
233 Sparc-64 4 MB
234 x86_64 2 MB
235 .TE
236 .RE
237 .SH BUGS
238 In the obsolete LinuxThreads implementation,
239 each of the threads in a process has a different process ID.
240 This is in violation of the POSIX threads specification,
241 and is the source of many other nonconformances to the standard; see
242 .BR pthreads (7).
243 .SH EXAMPLES
244 The program below demonstrates the use of
245 .BR pthread_create (),
246 as well as a number of other functions in the pthreads API.
247 .PP
248 In the following run,
249 on a system providing the NPTL threading implementation,
250 the stack size defaults to the value given by the
251 "stack size" resource limit:
252 .PP
253 .in +4n
254 .EX
255 .RB "$" " ulimit \-s"
256 8192 # The stack size limit is 8 MB (0x800000 bytes)
257 .RB "$" " ./a.out hola salut servus"
258 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
259 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
260 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
261 Joined with thread 1; returned value was HOLA
262 Joined with thread 2; returned value was SALUT
263 Joined with thread 3; returned value was SERVUS
264 .EE
265 .in
266 .PP
267 In the next run, the program explicitly sets a stack size of 1\ MB (using
268 .BR pthread_attr_setstacksize (3))
269 for the created threads:
270 .PP
271 .in +4n
272 .EX
273 .RB "$" " ./a.out \-s 0x100000 hola salut servus"
274 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
275 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
276 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
277 Joined with thread 1; returned value was HOLA
278 Joined with thread 2; returned value was SALUT
279 Joined with thread 3; returned value was SERVUS
280 .EE
281 .in
282 .SS Program source
283 \&
284 .EX
285 #include <pthread.h>
286 #include <string.h>
287 #include <stdio.h>
288 #include <stdlib.h>
289 #include <unistd.h>
290 #include <errno.h>
291 #include <ctype.h>
292
293 #define handle_error_en(en, msg) \e
294 do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
295
296 #define handle_error(msg) \e
297 do { perror(msg); exit(EXIT_FAILURE); } while (0)
298
299 struct thread_info { /* Used as argument to thread_start() */
300 pthread_t thread_id; /* ID returned by pthread_create() */
301 int thread_num; /* Application\-defined thread # */
302 char *argv_string; /* From command\-line argument */
303 };
304
305 /* Thread start function: display address near top of our stack,
306 and return upper\-cased copy of argv_string. */
307
308 static void *
309 thread_start(void *arg)
310 {
311 struct thread_info *tinfo = arg;
312 char *uargv;
313
314 printf("Thread %d: top of stack near %p; argv_string=%s\en",
315 tinfo\->thread_num, &p, tinfo\->argv_string);
316
317 uargv = strdup(tinfo\->argv_string);
318 if (uargv == NULL)
319 handle_error("strdup");
320
321 for (char *p = uargv; *p != \(aq\e0\(aq; p++)
322 *p = toupper(*p);
323
324 return uargv;
325 }
326
327 int
328 main(int argc, char *argv[])
329 {
330 int s, opt, num_threads;
331 pthread_attr_t attr;
332 size_t stack_size;
333 void *res;
334
335 /* The "\-s" option specifies a stack size for our threads. */
336
337 stack_size = \-1;
338 while ((opt = getopt(argc, argv, "s:")) != \-1) {
339 switch (opt) {
340 case \(aqs\(aq:
341 stack_size = strtoul(optarg, NULL, 0);
342 break;
343
344 default:
345 fprintf(stderr, "Usage: %s [\-s stack\-size] arg...\en",
346 argv[0]);
347 exit(EXIT_FAILURE);
348 }
349 }
350
351 num_threads = argc \- optind;
352
353 /* Initialize thread creation attributes. */
354
355 s = pthread_attr_init(&attr);
356 if (s != 0)
357 handle_error_en(s, "pthread_attr_init");
358
359 if (stack_size > 0) {
360 s = pthread_attr_setstacksize(&attr, stack_size);
361 if (s != 0)
362 handle_error_en(s, "pthread_attr_setstacksize");
363 }
364
365 /* Allocate memory for pthread_create() arguments. */
366
367 struct thread_info *tinfo = calloc(num_threads, sizeof(*tinfo));
368 if (tinfo == NULL)
369 handle_error("calloc");
370
371 /* Create one thread for each command\-line argument. */
372
373 for (int tnum = 0; tnum < num_threads; tnum++) {
374 tinfo[tnum].thread_num = tnum + 1;
375 tinfo[tnum].argv_string = argv[optind + tnum];
376
377 /* The pthread_create() call stores the thread ID into
378 corresponding element of tinfo[]. */
379
380 s = pthread_create(&tinfo[tnum].thread_id, &attr,
381 &thread_start, &tinfo[tnum]);
382 if (s != 0)
383 handle_error_en(s, "pthread_create");
384 }
385
386 /* Destroy the thread attributes object, since it is no
387 longer needed. */
388
389 s = pthread_attr_destroy(&attr);
390 if (s != 0)
391 handle_error_en(s, "pthread_attr_destroy");
392
393 /* Now join with each thread, and display its returned value. */
394
395 for (int tnum = 0; tnum < num_threads; tnum++) {
396 s = pthread_join(tinfo[tnum].thread_id, &res);
397 if (s != 0)
398 handle_error_en(s, "pthread_join");
399
400 printf("Joined with thread %d; returned value was %s\en",
401 tinfo[tnum].thread_num, (char *) res);
402 free(res); /* Free memory allocated by thread */
403 }
404
405 free(tinfo);
406 exit(EXIT_SUCCESS);
407 }
408 .EE
409 .SH SEE ALSO
410 .ad l
411 .nh
412 .BR getrlimit (2),
413 .BR pthread_attr_init (3),
414 .BR pthread_cancel (3),
415 .BR pthread_detach (3),
416 .BR pthread_equal (3),
417 .BR pthread_exit (3),
418 .BR pthread_getattr_np (3),
419 .BR pthread_join (3),
420 .BR pthread_self (3),
421 .BR pthread_setattr_default_np (3),
422 .BR pthreads (7)