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