]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man3/pthread_create.3
iconv.1, ldd.1, locale.1, localedef.1, memusage.1, memusagestat.1, mtrace.1, pldd...
[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 2017-09-15 "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 .TS
157 allbox;
158 lb lb lb
159 l l l.
160 Interface Attribute Value
161 T{
162 .BR pthread_create ()
163 T} Thread safety MT-Safe
164 .TE
165 .sp 1
166 .SH CONFORMING TO
167 POSIX.1-2001, POSIX.1-2008.
168 .SH NOTES
169 See
170 .BR pthread_self (3)
171 for further information on the thread ID returned in
172 .IR *thread
173 by
174 .BR pthread_create ().
175 Unless real-time scheduling policies are being employed,
176 after a call to
177 .BR pthread_create (),
178 it is indeterminate which thread\(emthe caller or the new thread\(emwill
179 next execute.
180 .PP
181 A thread may either be
182 .I joinable
183 or
184 .IR detached .
185 If a thread is joinable, then another thread can call
186 .BR pthread_join (3)
187 to wait for the thread to terminate and fetch its exit status.
188 Only when a terminated joinable thread has been joined are
189 the last of its resources released back to the system.
190 When a detached thread terminates,
191 its resources are automatically released back to the system:
192 it is not possible to join with the thread in order to obtain
193 its exit status.
194 Making a thread detached is useful for some types of daemon threads
195 whose exit status the application does not need to care about.
196 By default, a new thread is created in a joinable state, unless
197 .I attr
198 was set to create the thread in a detached state (using
199 .BR pthread_attr_setdetachstate (3)).
200 .PP
201 .\" FIXME . Perhaps some of the following detail should be in
202 .\" a future pthread_attr_setstacksize(3) page.
203 On Linux/x86-32, the default stack size for a new thread is 2 megabytes.
204 Under the NPTL threading implementation, if the
205 .BR RLIMIT_STACK
206 soft resource limit
207 .IR "at the time the program started"
208 has any value other than "unlimited",
209 then it determines the default stack size of new threads.
210 Using
211 .BR pthread_attr_setstacksize (3),
212 the stack size attribute can be explicitly set in the
213 .I attr
214 argument used to create a thread,
215 in order to obtain a stack size other than the default.
216 .SH BUGS
217 In the obsolete LinuxThreads implementation,
218 each of the threads in a process has a different process ID.
219 This is in violation of the POSIX threads specification,
220 and is the source of many other nonconformances to the standard; see
221 .BR pthreads (7).
222 .SH EXAMPLE
223 The program below demonstrates the use of
224 .BR pthread_create (),
225 as well as a number of other functions in the pthreads API.
226 .PP
227 In the following run,
228 on a system providing the NPTL threading implementation,
229 the stack size defaults to the value given by the
230 "stack size" resource limit:
231 .PP
232 .in +4n
233 .EX
234 .RB "$" " ulimit \-s"
235 8192 # The stack size limit is 8 MB (0x800000 bytes)
236 .RB "$" " ./a.out hola salut servus"
237 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
238 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
239 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
240 Joined with thread 1; returned value was HOLA
241 Joined with thread 2; returned value was SALUT
242 Joined with thread 3; returned value was SERVUS
243 .EE
244 .in
245 .PP
246 In the next run, the program explicitly sets a stack size of 1\ MB (using
247 .BR pthread_attr_setstacksize (3))
248 for the created threads:
249 .PP
250 .in +4n
251 .EX
252 .RB "$" " ./a.out \-s 0x100000 hola salut servus"
253 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
254 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
255 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
256 Joined with thread 1; returned value was HOLA
257 Joined with thread 2; returned value was SALUT
258 Joined with thread 3; returned value was SERVUS
259 .EE
260 .in
261 .SS Program source
262 \&
263 .EX
264 #include <pthread.h>
265 #include <string.h>
266 #include <stdio.h>
267 #include <stdlib.h>
268 #include <unistd.h>
269 #include <errno.h>
270 #include <ctype.h>
271
272 #define handle_error_en(en, msg) \\
273 do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
274
275 #define handle_error(msg) \\
276 do { perror(msg); exit(EXIT_FAILURE); } while (0)
277
278 struct thread_info { /* Used as argument to thread_start() */
279 pthread_t thread_id; /* ID returned by pthread_create() */
280 int thread_num; /* Application\-defined thread # */
281 char *argv_string; /* From command\-line argument */
282 };
283
284 /* Thread start function: display address near top of our stack,
285 and return upper\-cased copy of argv_string */
286
287 static void *
288 thread_start(void *arg)
289 {
290 struct thread_info *tinfo = arg;
291 char *uargv, *p;
292
293 printf("Thread %d: top of stack near %p; argv_string=%s\\n",
294 tinfo\->thread_num, &p, tinfo\->argv_string);
295
296 uargv = strdup(tinfo\->argv_string);
297 if (uargv == NULL)
298 handle_error("strdup");
299
300 for (p = uargv; *p != \(aq\\0\(aq; p++)
301 *p = toupper(*p);
302
303 return uargv;
304 }
305
306 int
307 main(int argc, char *argv[])
308 {
309 int s, tnum, opt, num_threads;
310 struct thread_info *tinfo;
311 pthread_attr_t attr;
312 int stack_size;
313 void *res;
314
315 /* The "\-s" option specifies a stack size for our threads */
316
317 stack_size = \-1;
318 while ((opt = getopt(argc, argv, "s:")) != \-1) {
319 switch (opt) {
320 case \(aqs\(aq:
321 stack_size = strtoul(optarg, NULL, 0);
322 break;
323
324 default:
325 fprintf(stderr, "Usage: %s [\-s stack-size] arg...\\n",
326 argv[0]);
327 exit(EXIT_FAILURE);
328 }
329 }
330
331 num_threads = argc \- optind;
332
333 /* Initialize thread creation attributes */
334
335 s = pthread_attr_init(&attr);
336 if (s != 0)
337 handle_error_en(s, "pthread_attr_init");
338
339 if (stack_size > 0) {
340 s = pthread_attr_setstacksize(&attr, stack_size);
341 if (s != 0)
342 handle_error_en(s, "pthread_attr_setstacksize");
343 }
344
345 /* Allocate memory for pthread_create() arguments */
346
347 tinfo = calloc(num_threads, sizeof(struct thread_info));
348 if (tinfo == NULL)
349 handle_error("calloc");
350
351 /* Create one thread for each command\-line argument */
352
353 for (tnum = 0; tnum < num_threads; tnum++) {
354 tinfo[tnum].thread_num = tnum + 1;
355 tinfo[tnum].argv_string = argv[optind + tnum];
356
357 /* The pthread_create() call stores the thread ID into
358 corresponding element of tinfo[] */
359
360 s = pthread_create(&tinfo[tnum].thread_id, &attr,
361 &thread_start, &tinfo[tnum]);
362 if (s != 0)
363 handle_error_en(s, "pthread_create");
364 }
365
366 /* Destroy the thread attributes object, since it is no
367 longer needed */
368
369 s = pthread_attr_destroy(&attr);
370 if (s != 0)
371 handle_error_en(s, "pthread_attr_destroy");
372
373 /* Now join with each thread, and display its returned value */
374
375 for (tnum = 0; tnum < num_threads; tnum++) {
376 s = pthread_join(tinfo[tnum].thread_id, &res);
377 if (s != 0)
378 handle_error_en(s, "pthread_join");
379
380 printf("Joined with thread %d; returned value was %s\\n",
381 tinfo[tnum].thread_num, (char *) res);
382 free(res); /* Free memory allocated by thread */
383 }
384
385 free(tinfo);
386 exit(EXIT_SUCCESS);
387 }
388 .EE
389 .SH SEE ALSO
390 .ad l
391 .nh
392 .BR getrlimit (2),
393 .BR pthread_attr_init (3),
394 .BR pthread_cancel (3),
395 .BR pthread_detach (3),
396 .BR pthread_equal (3),
397 .BR pthread_exit (3),
398 .BR pthread_getattr_np (3),
399 .BR pthread_join (3),
400 .BR pthread_self (3),
401 .BR pthread_setattr_default_np (3),
402 .BR pthreads (7)