OSDN Git Service

(split) LDP: Update original to LDP v3.38.
[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 .\" 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.
7 .\"
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.
12 .\"
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
19 .\" professionally.
20 .\"
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
23 .\"
24 .TH PTHREAD_CREATE 3 2012-03-15 "Linux" "Linux Programmer's Manual"
25 .SH NAME
26 pthread_create \- create a new thread
27 .SH SYNOPSIS
28 .nf
29 .B #include <pthread.h>
30
31 .BI "int pthread_create(pthread_t *" thread ", const pthread_attr_t *" attr ,
32 .BI "                   void *(*" start_routine ") (void *), void *" arg );
33 .fi
34 .sp
35 Compile and link with \fI\-pthread\fP.
36 .SH DESCRIPTION
37 The
38 .BR pthread_create ()
39 function starts a new thread in the calling process.
40 The new thread starts execution by invoking
41 .IR start_routine ();
42 .IR arg
43 is passed as the sole argument of
44 .IR start_routine ().
45
46 The new thread terminates in one of the following ways:
47 .IP * 2
48 It calls
49 .BR pthread_exit (3),
50 specifying an exit status value that is available to another thread
51 in the same process that calls
52 .BR pthread_join (3).
53 .IP *
54 It returns from
55 .IR start_routine ().
56 This is equivalent to calling
57 .BR pthread_exit (3)
58 with the value supplied in the
59 .I return
60 statement.
61 .IP *
62 It is canceled (see
63 .BR pthread_cancel (3)).
64 .IP *
65 Any of the threads in the process calls
66 .BR exit (3),
67 or the main thread performs a return from
68 .IR main ().
69 This causes the termination of all threads in the process.
70 .PP
71 The
72 .I attr
73 argument points to a
74 .I pthread_attr_t
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.
80 If
81 .I attr
82 is NULL,
83 then the thread is created with default attributes.
84
85 Before returning, a successful call to
86 .BR pthread_create ()
87 stores the ID of the new thread in the buffer pointed to by
88 .IR thread ;
89 this identifier is used to refer to the thread
90 in subsequent calls to other pthreads functions.
91
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)).
99
100 The new thread inherits the calling thread's floating-point environment
101 .RB ( fenv (3)).
102
103 The initial value of the new thread's CPU-time clock is 0
104 (see
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
109 (see
110 .BR capabilities (7))
111 and CPU affinity mask (see
112 .BR sched_setaffinity (2)).
113 .SH RETURN VALUE
114 On success,
115 .BR pthread_create ()
116 returns 0;
117 on error, it returns an error number, and the contents of
118 .IR *thread
119 are undefined.
120 .SH ERRORS
121 .TP
122 .B EAGAIN
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:
126 the
127 .BR RLIMIT_NPROC
128 soft resource limit (set via
129 .BR setrlimit (2)),
130 which limits the number of process for a real user ID,
131 was reached;
132 or the kernel's system-wide limit on the number of threads,
133 .IR /proc/sys/kernel/threads-max ,
134 was reached.
135 .TP
136 .B EINVAL
137 Invalid settings in
138 .IR attr .
139 .TP
140 .\" FIXME . Test the following
141 .B EPERM
142 No permission to set the scheduling policy and parameters specified in
143 .IR attr .
144 .SH CONFORMING TO
145 POSIX.1-2001.
146 .SH NOTES
147 See
148 .BR pthread_self (3)
149 for further information on the thread ID returned in
150 .IR *thread
151 by
152 .BR pthread_create ().
153 Unless real-time scheduling policies are being employed,
154 after a call to
155 .BR pthread_create (),
156 it is indeterminate which thread\(emthe caller or the new thread\(emwill
157 next execute.
158
159 A thread may either be
160 .I joinable
161 or
162 .IR detached .
163 If a thread is joinable, then another thread can call
164 .BR pthread_join (3)
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
171 its exit status.
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
175 .I attr
176 was set to create the thread in a detached state (using
177 .BR pthread_attr_setdetachstate (3)).
178
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
183 .BR RLIMIT_STACK
184 soft resource limit
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.
188 Using
189 .BR pthread_attr_setstacksize (3),
190 the stack size attribute can be explicitly set in the
191 .I attr
192 argument used to create a thread,
193 in order to obtain a stack size other than the default.
194 .SH BUGS
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
199 .BR pthreads (7).
200 .SH EXAMPLE
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.
204
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:
209
210 .in +4n
211 .nf
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
221 .fi
222 .in
223
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:
227
228 .in +4n
229 .nf
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
237 .fi
238 .in
239 .SS Program source
240 \&
241 .nf
242 #include <pthread.h>
243 #include <string.h>
244 #include <stdio.h>
245 #include <stdlib.h>
246 #include <unistd.h>
247 #include <errno.h>
248 #include <ctype.h>
249
250 #define handle_error_en(en, msg) \\
251         do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
252
253 #define handle_error(msg) \\
254         do { perror(msg); exit(EXIT_FAILURE); } while (0)
255
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 */
260 };
261
262 /* Thread start function: display address near top of our stack,
263    and return upper\-cased copy of argv_string */
264
265 static void *
266 thread_start(void *arg)
267 {
268     struct thread_info *tinfo = (struct thread_info *) arg;
269     char *uargv, *p;
270
271     printf("Thread %d: top of stack near %p; argv_string=%s\\n",
272             tinfo\->thread_num, &p, tinfo->argv_string);
273
274     uargv = strdup(tinfo\->argv_string);
275     if (uargv == NULL)
276         handle_error("strdup");
277
278     for (p = uargv; *p != \(aq\\0\(aq; p++)
279         *p = toupper(*p);
280
281     return uargv;
282 }
283
284 int
285 main(int argc, char *argv[])
286 {
287     int s, tnum, opt, num_threads;
288     struct thread_info *tinfo;
289     pthread_attr_t attr;
290     int stack_size;
291     void *res;
292
293     /* The "\-s" option specifies a stack size for our threads */
294
295     stack_size = \-1;
296     while ((opt = getopt(argc, argv, "s:")) != \-1) {
297         switch (opt) {
298         case \(aqs\(aq:
299             stack_size = strtoul(optarg, NULL, 0);
300             break;
301
302         default:
303             fprintf(stderr, "Usage: %s [\-s stack-size] arg...\\n",
304                     argv[0]);
305             exit(EXIT_FAILURE);
306         }
307     }
308
309     num_threads = argc \- optind;
310
311     /* Initialize thread creation attributes */
312
313     s = pthread_attr_init(&attr);
314     if (s != 0)
315         handle_error_en(s, "pthread_attr_init");
316
317     if (stack_size > 0) {
318         s = pthread_attr_setstacksize(&attr, stack_size);
319         if (s != 0)
320             handle_error_en(s, "pthread_attr_setstacksize");
321     }
322
323     /* Allocate memory for pthread_create() arguments */
324
325     tinfo = calloc(num_threads, sizeof(struct thread_info));
326     if (tinfo == NULL)
327         handle_error("calloc");
328
329     /* Create one thread for each command\-line argument */
330
331     for (tnum = 0; tnum < num_threads; tnum++) {
332         tinfo[tnum].thread_num = tnum + 1;
333         tinfo[tnum].argv_string = argv[optind + tnum];
334
335         /* The pthread_create() call stores the thread ID into
336            corresponding element of tinfo[] */
337
338         s = pthread_create(&tinfo[tnum].thread_id, &attr,
339                            &thread_start, &tinfo[tnum]);
340         if (s != 0)
341             handle_error_en(s, "pthread_create");
342     }
343
344     /* Destroy the thread attributes object, since it is no
345        longer needed */
346
347     s = pthread_attr_destroy(&attr);
348     if (s != 0)
349         handle_error_en(s, "pthread_attr_destroy");
350
351     /* Now join with each thread, and display its returned value */
352
353     for (tnum = 0; tnum < num_threads; tnum++) {
354         s = pthread_join(tinfo[tnum].thread_id, &res);
355         if (s != 0)
356             handle_error_en(s, "pthread_join");
357
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 */
361     }
362
363     free(tinfo);
364     exit(EXIT_SUCCESS);
365 }
366 .fi
367 .SH SEE ALSO
368 .BR getrlimit (2),
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),
377 .BR pthreads (7)