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 2012-03-15 "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 In the obsolete LinuxThreads implementation,
196 each of the threads in a process has a different process ID.
197 This is in violation of the POSIX threads specification,
198 and is the source of many other nonconformances to the standard; see
201 The program below demonstrates the use of
202 .BR pthread_create (),
203 as well as a number of other functions in the pthreads API.
205 In the following run,
206 on a system providing the NPTL threading implementation,
207 the stack size defaults to the value given by the
208 "stack size" resource limit:
212 .RB "$" " ulimit \-s"
213 8192 # The stack size limit is 8 MB (0x80000 bytes)
214 .RB "$" " ./a.out hola salut servus"
215 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
216 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
217 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
218 Joined with thread 1; returned value was HOLA
219 Joined with thread 2; returned value was SALUT
220 Joined with thread 3; returned value was SERVUS
224 In the next run, the program explicitly sets a stack size of 1MB (using
225 .BR pthread_attr_setstacksize (3))
226 for the created threads:
230 .RB "$" " ./a.out \-s 0x100000 hola salut servus"
231 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
232 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
233 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
234 Joined with thread 1; returned value was HOLA
235 Joined with thread 2; returned value was SALUT
236 Joined with thread 3; returned value was SERVUS
250 #define handle_error_en(en, msg) \\
251 do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
253 #define handle_error(msg) \\
254 do { perror(msg); exit(EXIT_FAILURE); } while (0)
256 struct thread_info { /* Used as argument to thread_start() */
257 pthread_t thread_id; /* ID returned by pthread_create() */
258 int thread_num; /* Application\-defined thread # */
259 char *argv_string; /* From command\-line argument */
262 /* Thread start function: display address near top of our stack,
263 and return upper\-cased copy of argv_string */
266 thread_start(void *arg)
268 struct thread_info *tinfo = (struct thread_info *) arg;
271 printf("Thread %d: top of stack near %p; argv_string=%s\\n",
272 tinfo\->thread_num, &p, tinfo->argv_string);
274 uargv = strdup(tinfo\->argv_string);
276 handle_error("strdup");
278 for (p = uargv; *p != \(aq\\0\(aq; p++)
285 main(int argc, char *argv[])
287 int s, tnum, opt, num_threads;
288 struct thread_info *tinfo;
293 /* The "\-s" option specifies a stack size for our threads */
296 while ((opt = getopt(argc, argv, "s:")) != \-1) {
299 stack_size = strtoul(optarg, NULL, 0);
303 fprintf(stderr, "Usage: %s [\-s stack-size] arg...\\n",
309 num_threads = argc \- optind;
311 /* Initialize thread creation attributes */
313 s = pthread_attr_init(&attr);
315 handle_error_en(s, "pthread_attr_init");
317 if (stack_size > 0) {
318 s = pthread_attr_setstacksize(&attr, stack_size);
320 handle_error_en(s, "pthread_attr_setstacksize");
323 /* Allocate memory for pthread_create() arguments */
325 tinfo = calloc(num_threads, sizeof(struct thread_info));
327 handle_error("calloc");
329 /* Create one thread for each command\-line argument */
331 for (tnum = 0; tnum < num_threads; tnum++) {
332 tinfo[tnum].thread_num = tnum + 1;
333 tinfo[tnum].argv_string = argv[optind + tnum];
335 /* The pthread_create() call stores the thread ID into
336 corresponding element of tinfo[] */
338 s = pthread_create(&tinfo[tnum].thread_id, &attr,
339 &thread_start, &tinfo[tnum]);
341 handle_error_en(s, "pthread_create");
344 /* Destroy the thread attributes object, since it is no
347 s = pthread_attr_destroy(&attr);
349 handle_error_en(s, "pthread_attr_destroy");
351 /* Now join with each thread, and display its returned value */
353 for (tnum = 0; tnum < num_threads; tnum++) {
354 s = pthread_join(tinfo[tnum].thread_id, &res);
356 handle_error_en(s, "pthread_join");
358 printf("Joined with thread %d; returned value was %s\\n",
359 tinfo[tnum].thread_num, (char *) res);
360 free(res); /* Free memory allocated by thread */
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),