OSDN Git Service

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