1 .\" Copyright (c) 2008 Linux Foundation, written by Michael Kerrisk
2 .\" <mtk.manpages@gmail.com>
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.
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.
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
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
26 .TH PTHREAD_CREATE 3 2014-05-28 "Linux" "Linux Programmer's Manual"
28 pthread_create \- create a new thread
31 .B #include <pthread.h>
33 .BI "int pthread_create(pthread_t *" thread ", const pthread_attr_t *" attr ,
34 .BI " void *(*" start_routine ") (void *), void *" arg );
37 Compile and link with \fI\-pthread\fP.
41 function starts a new thread in the calling process.
42 The new thread starts execution by invoking
45 is passed as the sole argument of
48 The new thread terminates in one of the following ways:
52 specifying an exit status value that is available to another thread
53 in the same process that calls
58 This is equivalent to calling
60 with the value supplied in the
65 .BR pthread_cancel (3)).
67 Any of the threads in the process calls
69 or the main thread performs a return from
71 This causes the termination of all threads in the process.
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.
85 then the thread is created with default attributes.
87 Before returning, a successful call to
89 stores the ID of the new thread in the buffer pointed to by
91 this identifier is used to refer to the thread
92 in subsequent calls to other pthreads functions.
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)).
102 The new thread inherits the calling thread's floating-point environment
105 The initial value of the new thread's CPU-time clock is 0
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
112 .BR capabilities (7))
113 and CPU affinity mask (see
114 .BR sched_setaffinity (2)).
117 .BR pthread_create ()
119 on error, it returns an error number, and the contents of
125 Insufficient resources to create another thread.
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
132 soft resource limit (set via
134 which limits the number of processes and threads for a real user ID,
136 the kernel's system-wide limit on the number of processes and threads,
137 .IR /proc/sys/kernel/threads-max ,
140 or the maximum number of PIDs,
141 .IR /proc/sys/kernel/pid_max ,
149 .\" FIXME . Test the following
151 No permission to set the scheduling policy and parameters specified in
158 for further information on the thread ID returned in
161 .BR pthread_create ().
162 Unless real-time scheduling policies are being employed,
164 .BR pthread_create (),
165 it is indeterminate which thread\(emthe caller or the new thread\(emwill
168 A thread may either be
172 If a thread is joinable, then another thread can call
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
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
185 was set to create the thread in a detached state (using
186 .BR pthread_attr_setdetachstate (3)).
188 .\" FIXME . Perhaps some of the following detail should be in
189 .\" a future pthread_attr_setstacksize(3) page.
190 On Linux/x86-32, the default stack size for a new thread is 2 megabytes.
191 Under the NPTL threading implementation, if the
194 .IR "at the time the program started"
195 has any value other than "unlimited",
196 then it determines the default stack size of new threads.
198 .BR pthread_attr_setstacksize (3),
199 the stack size attribute can be explicitly set in the
201 argument used to create a thread,
202 in order to obtain a stack size other than the default.
204 In the obsolete LinuxThreads implementation,
205 each of the threads in a process has a different process ID.
206 This is in violation of the POSIX threads specification,
207 and is the source of many other nonconformances to the standard; see
210 The program below demonstrates the use of
211 .BR pthread_create (),
212 as well as a number of other functions in the pthreads API.
214 In the following run,
215 on a system providing the NPTL threading implementation,
216 the stack size defaults to the value given by the
217 "stack size" resource limit:
221 .RB "$" " ulimit \-s"
222 8192 # The stack size limit is 8 MB (0x800000 bytes)
223 .RB "$" " ./a.out hola salut servus"
224 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
225 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
226 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
227 Joined with thread 1; returned value was HOLA
228 Joined with thread 2; returned value was SALUT
229 Joined with thread 3; returned value was SERVUS
233 In the next run, the program explicitly sets a stack size of 1MB (using
234 .BR pthread_attr_setstacksize (3))
235 for the created threads:
239 .RB "$" " ./a.out \-s 0x100000 hola salut servus"
240 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
241 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
242 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
243 Joined with thread 1; returned value was HOLA
244 Joined with thread 2; returned value was SALUT
245 Joined with thread 3; returned value was SERVUS
259 #define handle_error_en(en, msg) \\
260 do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
262 #define handle_error(msg) \\
263 do { perror(msg); exit(EXIT_FAILURE); } while (0)
265 struct thread_info { /* Used as argument to thread_start() */
266 pthread_t thread_id; /* ID returned by pthread_create() */
267 int thread_num; /* Application\-defined thread # */
268 char *argv_string; /* From command\-line argument */
271 /* Thread start function: display address near top of our stack,
272 and return upper\-cased copy of argv_string */
275 thread_start(void *arg)
277 struct thread_info *tinfo = arg;
280 printf("Thread %d: top of stack near %p; argv_string=%s\\n",
281 tinfo\->thread_num, &p, tinfo\->argv_string);
283 uargv = strdup(tinfo\->argv_string);
285 handle_error("strdup");
287 for (p = uargv; *p != \(aq\\0\(aq; p++)
294 main(int argc, char *argv[])
296 int s, tnum, opt, num_threads;
297 struct thread_info *tinfo;
302 /* The "\-s" option specifies a stack size for our threads */
305 while ((opt = getopt(argc, argv, "s:")) != \-1) {
308 stack_size = strtoul(optarg, NULL, 0);
312 fprintf(stderr, "Usage: %s [\-s stack-size] arg...\\n",
318 num_threads = argc \- optind;
320 /* Initialize thread creation attributes */
322 s = pthread_attr_init(&attr);
324 handle_error_en(s, "pthread_attr_init");
326 if (stack_size > 0) {
327 s = pthread_attr_setstacksize(&attr, stack_size);
329 handle_error_en(s, "pthread_attr_setstacksize");
332 /* Allocate memory for pthread_create() arguments */
334 tinfo = calloc(num_threads, sizeof(struct thread_info));
336 handle_error("calloc");
338 /* Create one thread for each command\-line argument */
340 for (tnum = 0; tnum < num_threads; tnum++) {
341 tinfo[tnum].thread_num = tnum + 1;
342 tinfo[tnum].argv_string = argv[optind + tnum];
344 /* The pthread_create() call stores the thread ID into
345 corresponding element of tinfo[] */
347 s = pthread_create(&tinfo[tnum].thread_id, &attr,
348 &thread_start, &tinfo[tnum]);
350 handle_error_en(s, "pthread_create");
353 /* Destroy the thread attributes object, since it is no
356 s = pthread_attr_destroy(&attr);
358 handle_error_en(s, "pthread_attr_destroy");
360 /* Now join with each thread, and display its returned value */
362 for (tnum = 0; tnum < num_threads; tnum++) {
363 s = pthread_join(tinfo[tnum].thread_id, &res);
365 handle_error_en(s, "pthread_join");
367 printf("Joined with thread %d; returned value was %s\\n",
368 tinfo[tnum].thread_num, (char *) res);
369 free(res); /* Free memory allocated by thread */
380 .BR pthread_attr_init (3),
381 .BR pthread_cancel (3),
382 .BR pthread_detach (3),
383 .BR pthread_equal (3),
384 .BR pthread_exit (3),
385 .BR pthread_getattr_np (3),
386 .BR pthread_join (3),
387 .BR pthread_self (3),
390 This page is part of release 3.79 of the Linux
393 A description of the project,
394 information about reporting bugs,
395 and the latest version of this page,
397 \%http://www.kernel.org/doc/man\-pages/.