1PTHREAD_CREATE(3) Linux Programmer's Manual PTHREAD_CREATE(3)
2
3
4
6 pthread_create - create a new thread
7
9 #include <pthread.h>
10
11 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
12 void *(*start_routine) (void *), void *arg);
13
14 Compile and link with -pthread.
15
17 The pthread_create() function starts a new thread in the calling
18 process. The new thread starts execution by invoking start_routine();
19 arg is passed as the sole argument of start_routine().
20
21 The new thread terminates in one of the following ways:
22
23 * It calls pthread_exit(3), specifying an exit status value that is
24 available to another thread in the same process that calls
25 pthread_join(3).
26
27 * It returns from start_routine(). This is equivalent to calling
28 pthread_exit(3) with the value supplied in the return statement.
29
30 * It is canceled (see pthread_cancel(3)).
31
32 * Any of the threads in the process calls exit(3), or the main thread
33 performs a return from main(). This causes the termination of all
34 threads in the process.
35
36 The attr argument points to a pthread_attr_t structure whose contents
37 are used at thread creation time to determine attributes for the new
38 thread; this structure is initialized using pthread_attr_init(3) and
39 related functions. If attr is NULL, then the thread is created with
40 default attributes.
41
42 Before returning, a successful call to pthread_create() stores the ID
43 of the new thread in the buffer pointed to by thread; this identifier
44 is used to refer to the thread in subsequent calls to other pthreads
45 functions.
46
47 The new thread inherits a copy of the creating thread's signal mask
48 (pthread_sigmask(3)). The set of pending signals for the new thread is
49 empty (sigpending(2)). The new thread does not inherit the creating
50 thread's alternate signal stack (sigaltstack(2)).
51
52 The new thread inherits the calling thread's floating-point environment
53 (fenv(3)).
54
55 The initial value of the new thread's CPU-time clock is 0 (see
56 pthread_getcpuclockid(3)).
57
58 Linux-specific details
59 The new thread inherits copies of the calling thread's capability sets
60 (see capabilities(7)) and CPU affinity mask (see sched_setaffinity(2)).
61
63 On success, pthread_create() returns 0; on error, it returns an error
64 number, and the contents of *thread are undefined.
65
67 EAGAIN Insufficient resources to create another thread, or a system-
68 imposed limit on the number of threads was encountered. The
69 latter case may occur in two ways: the RLIMIT_NPROC soft
70 resource limit (set via setrlimit(2)), which limits the number
71 of process for a real user ID, was reached; or the kernel's sys‐
72 tem-wide limit on the number of threads, /proc/sys/ker‐
73 nel/threads-max, was reached.
74
75 EINVAL Invalid settings in attr.
76
77 EPERM No permission to set the scheduling policy and parameters speci‐
78 fied in attr.
79
81 POSIX.1-2001.
82
84 See pthread_self(3) for further information on the thread ID returned
85 in *thread by pthread_create(). Unless real-time scheduling policies
86 are being employed, after a call to pthread_create(), it is indetermi‐
87 nate which thread—the caller or the new thread—will next execute.
88
89 A thread may either be joinable or detached. If a thread is joinable,
90 then another thread can call pthread_join(3) to wait for the thread to
91 terminate and fetch its exit status. Only when a terminated joinable
92 thread has been joined are the last of its resources released back to
93 the system. When a detached thread terminates, its resources are auto‐
94 matically released back to the system: it is not possible to join with
95 the thread in order to obtain its exit status. Making a thread
96 detached is useful for some types of daemon threads whose exit status
97 the application does not need to care about. By default, a new thread
98 is created in a joinable state, unless attr was set to create the
99 thread in a detached state (using pthread_attr_setdetachstate(3)).
100
101 On Linux/x86-32, the default stack size for a new thread is 2
102 megabytes. Under the NPTL threading implementation, if the
103 RLIMIT_STACK soft resource limit at the time the program started has
104 any value other than "unlimited", then it determines the default stack
105 size of new threads. Using pthread_attr_setstacksize(3), the stack
106 size attribute can be explicitly set in the attr argument used to cre‐
107 ate a thread, in order to obtain a stack size other than the default.
108
110 In the obsolete LinuxThreads implementation, each of the threads in a
111 process has a different process ID. This is in violation of the POSIX
112 threads specification, and is the source of many other nonconformances
113 to the standard; see pthreads(7).
114
116 The program below demonstrates the use of pthread_create(), as well as
117 a number of other functions in the pthreads API.
118
119 In the following run, on a system providing the NPTL threading imple‐
120 mentation, the stack size defaults to the value given by the "stack
121 size" resource limit:
122
123 $ ulimit -s
124 8192 # The stack size limit is 8 MB (0x800000 bytes)
125 $ ./a.out hola salut servus
126 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
127 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
128 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
129 Joined with thread 1; returned value was HOLA
130 Joined with thread 2; returned value was SALUT
131 Joined with thread 3; returned value was SERVUS
132
133 In the next run, the program explicitly sets a stack size of 1MB (using
134 pthread_attr_setstacksize(3)) for the created threads:
135
136 $ ./a.out -s 0x100000 hola salut servus
137 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
138 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
139 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
140 Joined with thread 1; returned value was HOLA
141 Joined with thread 2; returned value was SALUT
142 Joined with thread 3; returned value was SERVUS
143
144 Program source
145
146 #include <pthread.h>
147 #include <string.h>
148 #include <stdio.h>
149 #include <stdlib.h>
150 #include <unistd.h>
151 #include <errno.h>
152 #include <ctype.h>
153
154 #define handle_error_en(en, msg) \
155 do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
156
157 #define handle_error(msg) \
158 do { perror(msg); exit(EXIT_FAILURE); } while (0)
159
160 struct thread_info { /* Used as argument to thread_start() */
161 pthread_t thread_id; /* ID returned by pthread_create() */
162 int thread_num; /* Application-defined thread # */
163 char *argv_string; /* From command-line argument */
164 };
165
166 /* Thread start function: display address near top of our stack,
167 and return upper-cased copy of argv_string */
168
169 static void *
170 thread_start(void *arg)
171 {
172 struct thread_info *tinfo = arg;
173 char *uargv, *p;
174
175 printf("Thread %d: top of stack near %p; argv_string=%s\n",
176 tinfo->thread_num, &p, tinfo->argv_string);
177
178 uargv = strdup(tinfo->argv_string);
179 if (uargv == NULL)
180 handle_error("strdup");
181
182 for (p = uargv; *p != '\0'; p++)
183 *p = toupper(*p);
184
185 return uargv;
186 }
187
188 int
189 main(int argc, char *argv[])
190 {
191 int s, tnum, opt, num_threads;
192 struct thread_info *tinfo;
193 pthread_attr_t attr;
194 int stack_size;
195 void *res;
196
197 /* The "-s" option specifies a stack size for our threads */
198
199 stack_size = -1;
200 while ((opt = getopt(argc, argv, "s:")) != -1) {
201 switch (opt) {
202 case 's':
203 stack_size = strtoul(optarg, NULL, 0);
204 break;
205
206 default:
207 fprintf(stderr, "Usage: %s [-s stack-size] arg...\n",
208 argv[0]);
209 exit(EXIT_FAILURE);
210 }
211 }
212
213 num_threads = argc - optind;
214
215 /* Initialize thread creation attributes */
216
217 s = pthread_attr_init(&attr);
218 if (s != 0)
219 handle_error_en(s, "pthread_attr_init");
220
221 if (stack_size > 0) {
222 s = pthread_attr_setstacksize(&attr, stack_size);
223 if (s != 0)
224 handle_error_en(s, "pthread_attr_setstacksize");
225 }
226
227 /* Allocate memory for pthread_create() arguments */
228
229 tinfo = calloc(num_threads, sizeof(struct thread_info));
230 if (tinfo == NULL)
231 handle_error("calloc");
232
233 /* Create one thread for each command-line argument */
234
235 for (tnum = 0; tnum < num_threads; tnum++) {
236 tinfo[tnum].thread_num = tnum + 1;
237 tinfo[tnum].argv_string = argv[optind + tnum];
238
239 /* The pthread_create() call stores the thread ID into
240 corresponding element of tinfo[] */
241
242 s = pthread_create(&tinfo[tnum].thread_id, &attr,
243 &thread_start, &tinfo[tnum]);
244 if (s != 0)
245 handle_error_en(s, "pthread_create");
246 }
247
248 /* Destroy the thread attributes object, since it is no
249 longer needed */
250
251 s = pthread_attr_destroy(&attr);
252 if (s != 0)
253 handle_error_en(s, "pthread_attr_destroy");
254
255 /* Now join with each thread, and display its returned value */
256
257 for (tnum = 0; tnum < num_threads; tnum++) {
258 s = pthread_join(tinfo[tnum].thread_id, &res);
259 if (s != 0)
260 handle_error_en(s, "pthread_join");
261
262 printf("Joined with thread %d; returned value was %s\n",
263 tinfo[tnum].thread_num, (char *) res);
264 free(res); /* Free memory allocated by thread */
265 }
266
267 free(tinfo);
268 exit(EXIT_SUCCESS);
269 }
270
272 getrlimit(2), pthread_attr_init(3), pthread_cancel(3),
273 pthread_detach(3), pthread_equal(3), pthread_exit(3),
274 pthread_getattr_np(3), pthread_join(3), pthread_self(3), pthreads(7)
275
277 This page is part of release 3.53 of the Linux man-pages project. A
278 description of the project, and information about reporting bugs, can
279 be found at http://www.kernel.org/doc/man-pages/.
280
281
282
283Linux 2012-08-03 PTHREAD_CREATE(3)