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