malloc_get_state.3: tfix
[man-pages.git] / man3 / pthread_create.3
blob66c67a6ff3f33508f16603acfd93c3ce41c77b0f
1 '\" t
2 .\" Copyright (c) 2008 Linux Foundation, written by Michael Kerrisk
3 .\"     <mtk.manpages@gmail.com>
4 .\"
5 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
6 .\"
7 .TH pthread_create 3 (date) "Linux man-pages (unreleased)"
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>
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 ().
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.
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.
67 .I attr
68 is NULL,
69 then the thread is created with default attributes.
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.
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)).
86 The new thread inherits the calling thread's floating-point environment
87 .RB ( fenv (3)).
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
108 .B EAGAIN
109 Insufficient resources to create another thread.
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)).
129 .B EINVAL
130 Invalid settings in
131 .IR attr .
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).
141 allbox;
142 lbx lb lb
143 l l l.
144 Interface       Attribute       Value
148 .BR pthread_create ()
149 T}      Thread safety   MT-Safe
151 .SH STANDARDS
152 POSIX.1-2008.
153 .SH HISTORY
154 POSIX.1-2001.
155 .SH NOTES
157 .BR pthread_self (3)
158 for further information on the thread ID returned in
159 .I *thread
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.
168 A thread may either be
169 .I joinable
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)).
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 Here is the value for a few architectures:
207 allbox;
208 lb lb
209 l r.
210 Architecture    Default stack size
211 i386    2 MB
212 IA-64   32 MB
213 PowerPC 4 MB
214 S/390   2 MB
215 Sparc-32        2 MB
216 Sparc-64        4 MB
217 x86_64  2 MB
220 .SH BUGS
221 In the obsolete LinuxThreads implementation,
222 each of the threads in a process has a different process ID.
223 This is in violation of the POSIX threads specification,
224 and is the source of many other nonconformances to the standard; see
225 .BR pthreads (7).
226 .SH EXAMPLES
227 The program below demonstrates the use of
228 .BR pthread_create (),
229 as well as a number of other functions in the pthreads API.
231 In the following run,
232 on a system providing the NPTL threading implementation,
233 the stack size defaults to the value given by the
234 "stack size" resource limit:
236 .in +4n
238 .RB "$" " ulimit \-s"
239 8192            # The stack size limit is 8 MB (0x800000 bytes)
240 .RB "$" " ./a.out hola salut servus"
241 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
242 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
243 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
244 Joined with thread 1; returned value was HOLA
245 Joined with thread 2; returned value was SALUT
246 Joined with thread 3; returned value was SERVUS
250 In the next run, the program explicitly sets a stack size of 1\ MB (using
251 .BR pthread_attr_setstacksize (3))
252 for the created threads:
254 .in +4n
256 .RB "$" " ./a.out \-s 0x100000 hola salut servus"
257 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
258 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
259 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
260 Joined with thread 1; returned value was HOLA
261 Joined with thread 2; returned value was SALUT
262 Joined with thread 3; returned value was SERVUS
265 .SS Program source
267 .\" SRC BEGIN (pthread_create.c)
269 #include <ctype.h>
270 #include <errno.h>
271 #include <pthread.h>
272 #include <stdio.h>
273 #include <stdlib.h>
274 #include <string.h>
275 #include <unistd.h>
277 #define handle_error_en(en, msg) \e
278         do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
280 #define handle_error(msg) \e
281         do { perror(msg); exit(EXIT_FAILURE); } while (0)
283 struct thread_info {    /* Used as argument to thread_start() */
284     pthread_t thread_id;        /* ID returned by pthread_create() */
285     int       thread_num;       /* Application\-defined thread # */
286     char     *argv_string;      /* From command\-line argument */
289 /* Thread start function: display address near top of our stack,
290    and return upper\-cased copy of argv_string. */
292 static void *
293 thread_start(void *arg)
295     struct thread_info *tinfo = arg;
296     char *uargv;
298     printf("Thread %d: top of stack near %p; argv_string=%s\en",
299            tinfo\->thread_num, (void *) &tinfo, tinfo\->argv_string);
301     uargv = strdup(tinfo\->argv_string);
302     if (uargv == NULL)
303         handle_error("strdup");
305     for (char *p = uargv; *p != \[aq]\e0\[aq]; p++)
306         *p = toupper(*p);
308     return uargv;
312 main(int argc, char *argv[])
314     int                 s, opt;
315     void                *res;
316     size_t              num_threads;
317     ssize_t             stack_size;
318     pthread_attr_t      attr;
319     struct thread_info  *tinfo;
321     /* The "\-s" option specifies a stack size for our threads. */
323     stack_size = \-1;
324     while ((opt = getopt(argc, argv, "s:")) != \-1) {
325         switch (opt) {
326         case \[aq]s\[aq]:
327             stack_size = strtoul(optarg, NULL, 0);
328             break;
330         default:
331             fprintf(stderr, "Usage: %s [\-s stack\-size] arg...\en",
332                     argv[0]);
333             exit(EXIT_FAILURE);
334         }
335     }
337     num_threads = argc \- optind;
339     /* Initialize thread creation attributes. */
341     s = pthread_attr_init(&attr);
342     if (s != 0)
343         handle_error_en(s, "pthread_attr_init");
345     if (stack_size > 0) {
346         s = pthread_attr_setstacksize(&attr, stack_size);
347         if (s != 0)
348             handle_error_en(s, "pthread_attr_setstacksize");
349     }
351     /* Allocate memory for pthread_create() arguments. */
353     tinfo = calloc(num_threads, sizeof(*tinfo));
354     if (tinfo == NULL)
355         handle_error("calloc");
357     /* Create one thread for each command\-line argument. */
359     for (size_t tnum = 0; tnum < num_threads; tnum++) {
360         tinfo[tnum].thread_num = tnum + 1;
361         tinfo[tnum].argv_string = argv[optind + tnum];
363         /* The pthread_create() call stores the thread ID into
364            corresponding element of tinfo[]. */
366         s = pthread_create(&tinfo[tnum].thread_id, &attr,
367                            &thread_start, &tinfo[tnum]);
368         if (s != 0)
369             handle_error_en(s, "pthread_create");
370     }
372     /* Destroy the thread attributes object, since it is no
373        longer needed. */
375     s = pthread_attr_destroy(&attr);
376     if (s != 0)
377         handle_error_en(s, "pthread_attr_destroy");
379     /* Now join with each thread, and display its returned value. */
381     for (size_t tnum = 0; tnum < num_threads; tnum++) {
382         s = pthread_join(tinfo[tnum].thread_id, &res);
383         if (s != 0)
384             handle_error_en(s, "pthread_join");
386         printf("Joined with thread %d; returned value was %s\en",
387                tinfo[tnum].thread_num, (char *) res);
388         free(res);      /* Free memory allocated by thread */
389     }
391     free(tinfo);
392     exit(EXIT_SUCCESS);
395 .\" SRC END
396 .SH SEE ALSO
397 .ad l
399 .BR getrlimit (2),
400 .BR pthread_attr_init (3),
401 .BR pthread_cancel (3),
402 .BR pthread_detach (3),
403 .BR pthread_equal (3),
404 .BR pthread_exit (3),
405 .BR pthread_getattr_np (3),
406 .BR pthread_join (3),
407 .BR pthread_self (3),
408 .BR pthread_setattr_default_np (3),
409 .BR pthreads (7)