Debian Codegraph @

upstream/debian-trixie/man3/pthread_create.3

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