1 .\" Copyright (c) 2008 Linux Foundation, written by Michael Kerrisk
2 .\" <mtk.manpages@gmail.com>
4 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
8 .\" Permission is granted to copy and distribute modified versions of this
9 .\" manual under the conditions for verbatim copying, provided that the
10 .\" entire resulting derived work is distributed under the terms of a
11 .\" permission notice identical to this one.
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date. The author(s) assume no
15 .\" responsibility for errors or omissions, or for damages resulting from
16 .\" the use of the information contained herein. The author(s) may not
17 .\" have taken the same level of care in the production of this manual,
18 .\" which is licensed free of charge, as they might when working
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
24 .TH PTHREAD_CREATE 3 2008-11-11 "Linux" "Linux Programmer's Manual"
26 pthread_create \- create a new thread
29 .B #include <pthread.h>
31 .BI "int pthread_create(pthread_t *" thread ", const pthread_attr_t *" attr ,
32 .BI " void *(*" start_routine ") (void *), void *" arg );
35 Compile and link with \fI\-pthread\fP.
39 function starts a new thread in the calling process.
40 The new thread starts execution by invoking
43 is passed as the sole argument of
46 The new thread terminates in one of the following ways:
50 specifying an exit status value that is available to another thread
51 in the same process that calls
56 This is equivalent to calling
58 with the value supplied in the
63 .BR pthread_cancel (3)).
65 Any of the threads in the process calls
67 or the main thread performs a return from
69 This causes the termination of all threads in the process.
75 structure whose contents are used at thread creation time to
76 determine attributes for the new thread;
77 this structure is initialized using
78 .BR pthread_attr_init (3)
79 and related functions.
83 then the thread is created with default attributes.
85 Before returning, a successful call to
87 stores the ID of the new thread in the buffer pointed to by
89 this identifier is used to refer to the thread
90 in subsequent calls to other pthreads functions.
92 The new thread inherits a copy of the creating thread's signal mask
93 .RB ( pthread_sigmask (3)).
94 The set of pending signals for the new thread is empty
95 .RB ( sigpending (2)).
96 The new thread does not inherit the creating thread's
97 alternate signal stack
98 .RB ( sigaltstack (2)).
100 The new thread inherits the calling thread's floating-point environment
103 The initial value of the new thread's CPU-time clock is 0
105 .BR pthread_getcpuclockid (3)).
106 .\" CLOCK_THREAD_CPUTIME_ID in clock_gettime(2)
107 .SS Linux-specific details
108 The new thread inherits copies of the calling thread's capability sets
110 .BR capabilities (7))
111 and CPU affinity mask (see
112 .BR sched_setaffinity (2)).
115 .BR pthread_create ()
117 on error, it returns an error number, and the contents of
123 Insufficient resources to create another thread,
124 or a system-imposed limit on the number of threads was encountered.
125 The latter case may occur in two ways:
128 soft resource limit (set via
130 which limits the number of process for a real user ID,
132 or the kernel's system-wide limit on the number of threads,
133 .IR /proc/sys/kernel/threads-max ,
140 .\" FIXME . Test the following
142 No permission to set the scheduling policy and parameters specified in
149 for further information on the thread ID returned in
152 .BR pthread_create ().
153 Unless real-time scheduling policies are being employed,
155 .BR pthread_create (),
156 it is indeterminate which thread\(emthe caller or the new thread\(emwill
159 A thread may either be
163 If a thread is joinable, then another thread can call
165 to wait for the thread to terminate and fetch its exit status.
166 Only when a terminated joinable thread has been joined are
167 the last of its resources released back to the system.
168 When a detached thread terminates,
169 its resources are automatically released back to the system:
170 it is not possible to join with the thread in order to obtain
172 Making a thread detached is useful for some types of daemon threads
173 whose exit status the application does not need to care about.
174 By default, a new thread is created in a joinable state, unless
176 was set to create the thread in a detached state (using
177 .BR pthread_attr_setdetachstate (3)).
179 .\" FIXME . Perhaps some of the following detail should be in
180 .\" a future pthread_attr_setstacksize(3) page.
181 On Linux/x86-32, the default stack size for a new thread is 2 megabytes.
182 Under the NPTL threading implementation, if the
185 .IR "at the time the program started"
186 has any value other than "unlimited",
187 then it determines the default stack size of new threads.
189 .BR pthread_attr_setstacksize (3),
190 the stack size attribute can be explicitly set in the
192 argument used to create a thread,
193 in order to obtain a stack size other than the default.
195 The program below demonstrates the use of
196 .BR pthread_create (),
197 as well as a number of other functions in the pthreads API.
199 In the following run,
200 on a system providing the NPTL threading implementation,
201 the stack size defaults to the value given by the
202 "stack size" resource limit:
206 .RB "$" " ulimit \-s"
207 8192 # The stack size limit is 8 MB (0x80000 bytes)
208 .RB "$" " ./a.out hola salut servus"
209 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
210 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
211 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
212 Joined with thread 1; returned value was HOLA
213 Joined with thread 2; returned value was SALUT
214 Joined with thread 3; returned value was SERVUS
218 In the next run, the program explicitly sets a stack size of 1MB (using
219 .BR pthread_attr_setstacksize (3))
220 for the created threads:
224 .RB "$" " ./a.out \-s 0x100000 hola salut servus"
225 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
226 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
227 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
228 Joined with thread 1; returned value was HOLA
229 Joined with thread 2; returned value was SALUT
230 Joined with thread 3; returned value was SERVUS
244 #define handle_error_en(en, msg) \\
245 do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
247 #define handle_error(msg) \\
248 do { perror(msg); exit(EXIT_FAILURE); } while (0)
250 struct thread_info { /* Used as argument to thread_start() */
251 pthread_t thread_id; /* ID returned by pthread_create() */
252 int thread_num; /* Application\-defined thread # */
253 char *argv_string; /* From command\-line argument */
256 /* Thread start function: display address near top of our stack,
257 and return upper\-cased copy of argv_string */
260 thread_start(void *arg)
262 struct thread_info *tinfo = (struct thread_info *) arg;
265 printf("Thread %d: top of stack near %p; argv_string=%s\\n",
266 tinfo\->thread_num, &p, tinfo->argv_string);
268 uargv = strdup(tinfo\->argv_string);
270 handle_error("strdup");
272 for (p = uargv; *p != \(aq\\0\(aq; p++)
279 main(int argc, char *argv[])
281 int s, tnum, opt, num_threads;
282 struct thread_info *tinfo;
287 /* The "\-s" option specifies a stack size for our threads */
290 while ((opt = getopt(argc, argv, "s:")) != \-1) {
293 stack_size = strtoul(optarg, NULL, 0);
297 fprintf(stderr, "Usage: %s [\-s stack-size] arg...\\n",
303 num_threads = argc \- optind;
305 /* Initialize thread creation attributes */
307 s = pthread_attr_init(&attr);
309 handle_error_en(s, "pthread_attr_init");
311 if (stack_size > 0) {
312 s = pthread_attr_setstacksize(&attr, stack_size);
314 handle_error_en(s, "pthread_attr_setstacksize");
317 /* Allocate memory for pthread_create() arguments */
319 tinfo = calloc(num_threads, sizeof(struct thread_info));
321 handle_error("calloc");
323 /* Create one thread for each command\-line argument */
325 for (tnum = 0; tnum < num_threads; tnum++) {
326 tinfo[tnum].thread_num = tnum + 1;
327 tinfo[tnum].argv_string = argv[optind + tnum];
329 /* The pthread_create() call stores the thread ID into
330 corresponding element of tinfo[] */
332 s = pthread_create(&tinfo[tnum].thread_id, &attr,
333 &thread_start, &tinfo[tnum]);
335 handle_error_en(s, "pthread_create");
338 /* Destroy the thread attributes object, since it is no
341 s = pthread_attr_destroy(&attr);
343 handle_error_en(s, "pthread_attr_destroy");
345 /* Now join with each thread, and display its returned value */
347 for (tnum = 0; tnum < num_threads; tnum++) {
348 s = pthread_join(tinfo[tnum].thread_id, &res);
350 handle_error_en(s, "pthread_join");
352 printf("Joined with thread %d; returned value was %s\\n",
353 tinfo[tnum].thread_num, (char *) res);
354 free(res); /* Free memory allocated by thread */
362 In the obsolete LinuxThreads implementation,
363 each of the threads in a process has a different process ID.
364 This is in violation of the POSIX threads specification,
365 and is the source of many other nonconformances to the standard; see
369 .BR pthread_attr_init (3),
370 .BR pthread_cancel (3),
371 .BR pthread_detach (3),
372 .BR pthread_equal (3),
373 .BR pthread_exit (3),
374 .BR pthread_getattr_np (3),
375 .BR pthread_join (3),
376 .BR pthread_self (3),