OSDN Git Service

7264769412092a4e3538f190d61771571620af4a
[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 2008-11-11 "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 EXAMPLE
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.
198
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:
203
204 .in +4n
205 .nf
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
215 .fi
216 .in
217
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:
221
222 .in +4n
223 .nf
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
231 .fi
232 .in
233 .SS Program source
234 \&
235 .nf
236 #include <pthread.h>
237 #include <string.h>
238 #include <stdio.h>
239 #include <stdlib.h>
240 #include <unistd.h>
241 #include <errno.h>
242 #include <ctype.h>
243
244 #define handle_error_en(en, msg) \\
245         do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
246
247 #define handle_error(msg) \\
248         do { perror(msg); exit(EXIT_FAILURE); } while (0)
249
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 */
254 };
255
256 /* Thread start function: display address near top of our stack,
257    and return upper\-cased copy of argv_string */
258
259 static void *
260 thread_start(void *arg)
261 {
262     struct thread_info *tinfo = (struct thread_info *) arg;
263     char *uargv, *p;
264
265     printf("Thread %d: top of stack near %p; argv_string=%s\\n",
266             tinfo\->thread_num, &p, tinfo->argv_string);
267
268     uargv = strdup(tinfo\->argv_string);
269     if (uargv == NULL)
270         handle_error("strdup");
271
272     for (p = uargv; *p != \(aq\\0\(aq; p++)
273         *p = toupper(*p);
274
275     return uargv;
276 }
277
278 int
279 main(int argc, char *argv[])
280 {
281     int s, tnum, opt, num_threads;
282     struct thread_info *tinfo;
283     pthread_attr_t attr;
284     int stack_size;
285     void *res;
286
287     /* The "\-s" option specifies a stack size for our threads */
288
289     stack_size = \-1;
290     while ((opt = getopt(argc, argv, "s:")) != \-1) {
291         switch (opt) {
292         case \(aqs\(aq:
293             stack_size = strtoul(optarg, NULL, 0);
294             break;
295
296         default:
297             fprintf(stderr, "Usage: %s [\-s stack-size] arg...\\n",
298                     argv[0]);
299             exit(EXIT_FAILURE);
300         }
301     }
302
303     num_threads = argc \- optind;
304
305     /* Initialize thread creation attributes */
306
307     s = pthread_attr_init(&attr);
308     if (s != 0)
309         handle_error_en(s, "pthread_attr_init");
310
311     if (stack_size > 0) {
312         s = pthread_attr_setstacksize(&attr, stack_size);
313         if (s != 0)
314             handle_error_en(s, "pthread_attr_setstacksize");
315     }
316
317     /* Allocate memory for pthread_create() arguments */
318
319     tinfo = calloc(num_threads, sizeof(struct thread_info));
320     if (tinfo == NULL)
321         handle_error("calloc");
322
323     /* Create one thread for each command\-line argument */
324
325     for (tnum = 0; tnum < num_threads; tnum++) {
326         tinfo[tnum].thread_num = tnum + 1;
327         tinfo[tnum].argv_string = argv[optind + tnum];
328
329         /* The pthread_create() call stores the thread ID into
330            corresponding element of tinfo[] */
331
332         s = pthread_create(&tinfo[tnum].thread_id, &attr,
333                            &thread_start, &tinfo[tnum]);
334         if (s != 0)
335             handle_error_en(s, "pthread_create");
336     }
337
338     /* Destroy the thread attributes object, since it is no
339        longer needed */
340
341     s = pthread_attr_destroy(&attr);
342     if (s != 0)
343         handle_error_en(s, "pthread_attr_destroy");
344
345     /* Now join with each thread, and display its returned value */
346
347     for (tnum = 0; tnum < num_threads; tnum++) {
348         s = pthread_join(tinfo[tnum].thread_id, &res);
349         if (s != 0)
350             handle_error_en(s, "pthread_join");
351
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 */
355     }
356
357     free(tinfo);
358     exit(EXIT_SUCCESS);
359 }
360 .fi
361 .SH BUGS
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
366 .BR pthreads (7).
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)