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