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
106 indeterminate which thread—the caller or the new thread—will next
107 execute.
108
109 A thread may either be joinable or detached. If a thread is joinable,
110 then another thread can call pthread_join(3) to wait for the thread to
111 terminate and fetch its exit status. Only when a terminated joinable
112 thread has been joined are the last of its resources released back to
113 the system. When a detached thread terminates, its resources are
114 automatically released back to the system: it is not possible to join
115 with the thread in order to obtain its exit status. Making a thread
116 detached is useful for some types of daemon threads whose exit status
117 the application does not need to care about. By default, a new thread
118 is created in a joinable state, unless attr was set to create the
119 thread in a detached state (using pthread_attr_setdetachstate(3)).
120
121 Under the NPTL threading implementation, if the RLIMIT_STACK soft
122 resource limit at the time the program started has any value other than
123 "unlimited", then it determines the default stack size of new threads.
124 Using pthread_attr_setstacksize(3), the stack size attribute can be
125 explicitly set in the attr argument used to create a thread, in order
126 to obtain a stack size other than the default. If the RLIMIT_STACK
127 resource limit is set to "unlimited", a per-architecture value is used
128 for the stack size. Here is the value for a few architectures:
129
130 ┌─────────────┬────────────────────┐
131 │Architecture │ Default stack size │
132 ├─────────────┼────────────────────┤
133 │i386 │ 2 MB │
134 ├─────────────┼────────────────────┤
135 │IA-64 │ 32 MB │
136 ├─────────────┼────────────────────┤
137 │PowerPC │ 4 MB │
138 ├─────────────┼────────────────────┤
139 │S/390 │ 2 MB │
140 ├─────────────┼────────────────────┤
141 │Sparc-32 │ 2 MB │
142 ├─────────────┼────────────────────┤
143 │Sparc-64 │ 4 MB │
144 ├─────────────┼────────────────────┤
145 │x86_64 │ 2 MB │
146 └─────────────┴────────────────────┘
148 In the obsolete LinuxThreads implementation, each of the threads in a
149 process has a different process ID. This is in violation of the POSIX
150 threads specification, and is the source of many other nonconformances
151 to the standard; see pthreads(7).
152
154 The program below demonstrates the use of pthread_create(), as well as
155 a number of other functions in the pthreads API.
156
157 In the following run, on a system providing the NPTL threading
158 implementation, the stack size defaults to the value given by the
159 "stack size" resource limit:
160
161 $ ulimit -s
162 8192 # The stack size limit is 8 MB (0x800000 bytes)
163 $ ./a.out hola salut servus
164 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
165 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
166 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
167 Joined with thread 1; returned value was HOLA
168 Joined with thread 2; returned value was SALUT
169 Joined with thread 3; returned value was SERVUS
170
171 In the next run, the program explicitly sets a stack size of 1 MB (us‐
172 ing pthread_attr_setstacksize(3)) for the created threads:
173
174 $ ./a.out -s 0x100000 hola salut servus
175 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
176 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
177 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
178 Joined with thread 1; returned value was HOLA
179 Joined with thread 2; returned value was SALUT
180 Joined with thread 3; returned value was SERVUS
181
182 Program source
183
184 #include <ctype.h>
185 #include <errno.h>
186 #include <pthread.h>
187 #include <stdio.h>
188 #include <stdlib.h>
189 #include <string.h>
190 #include <unistd.h>
191
192 #define handle_error_en(en, msg) \
193 do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
194
195 #define handle_error(msg) \
196 do { perror(msg); exit(EXIT_FAILURE); } while (0)
197
198 struct thread_info { /* Used as argument to thread_start() */
199 pthread_t thread_id; /* ID returned by pthread_create() */
200 int thread_num; /* Application-defined thread # */
201 char *argv_string; /* From command-line argument */
202 };
203
204 /* Thread start function: display address near top of our stack,
205 and return upper-cased copy of argv_string. */
206
207 static void *
208 thread_start(void *arg)
209 {
210 struct thread_info *tinfo = arg;
211 char *uargv;
212
213 printf("Thread %d: top of stack near %p; argv_string=%s\n",
214 tinfo->thread_num, (void *) &tinfo, tinfo->argv_string);
215
216 uargv = strdup(tinfo->argv_string);
217 if (uargv == NULL)
218 handle_error("strdup");
219
220 for (char *p = uargv; *p != '\0'; p++)
221 *p = toupper(*p);
222
223 return uargv;
224 }
225
226 int
227 main(int argc, char *argv[])
228 {
229 int s, opt;
230 void *res;
231 size_t num_threads;
232 ssize_t stack_size;
233 pthread_attr_t attr;
234 struct thread_info *tinfo;
235
236 /* The "-s" option specifies a stack size for our threads. */
237
238 stack_size = -1;
239 while ((opt = getopt(argc, argv, "s:")) != -1) {
240 switch (opt) {
241 case 's':
242 stack_size = strtoul(optarg, NULL, 0);
243 break;
244
245 default:
246 fprintf(stderr, "Usage: %s [-s stack-size] arg...\n",
247 argv[0]);
248 exit(EXIT_FAILURE);
249 }
250 }
251
252 num_threads = argc - optind;
253
254 /* Initialize thread creation attributes. */
255
256 s = pthread_attr_init(&attr);
257 if (s != 0)
258 handle_error_en(s, "pthread_attr_init");
259
260 if (stack_size > 0) {
261 s = pthread_attr_setstacksize(&attr, stack_size);
262 if (s != 0)
263 handle_error_en(s, "pthread_attr_setstacksize");
264 }
265
266 /* Allocate memory for pthread_create() arguments. */
267
268 tinfo = calloc(num_threads, sizeof(*tinfo));
269 if (tinfo == NULL)
270 handle_error("calloc");
271
272 /* Create one thread for each command-line argument. */
273
274 for (size_t tnum = 0; tnum < num_threads; tnum++) {
275 tinfo[tnum].thread_num = tnum + 1;
276 tinfo[tnum].argv_string = argv[optind + tnum];
277
278 /* The pthread_create() call stores the thread ID into
279 corresponding element of tinfo[]. */
280
281 s = pthread_create(&tinfo[tnum].thread_id, &attr,
282 &thread_start, &tinfo[tnum]);
283 if (s != 0)
284 handle_error_en(s, "pthread_create");
285 }
286
287 /* Destroy the thread attributes object, since it is no
288 longer needed. */
289
290 s = pthread_attr_destroy(&attr);
291 if (s != 0)
292 handle_error_en(s, "pthread_attr_destroy");
293
294 /* Now join with each thread, and display its returned value. */
295
296 for (size_t tnum = 0; tnum < num_threads; tnum++) {
297 s = pthread_join(tinfo[tnum].thread_id, &res);
298 if (s != 0)
299 handle_error_en(s, "pthread_join");
300
301 printf("Joined with thread %d; returned value was %s\n",
302 tinfo[tnum].thread_num, (char *) res);
303 free(res); /* Free memory allocated by thread */
304 }
305
306 free(tinfo);
307 exit(EXIT_SUCCESS);
308 }
309
311 getrlimit(2), pthread_attr_init(3), pthread_cancel(3),
312 pthread_detach(3), pthread_equal(3), pthread_exit(3),
313 pthread_getattr_np(3), pthread_join(3), pthread_self(3),
314 pthread_setattr_default_np(3), pthreads(7)
315
316
317
318Linux man-pages 6.05 2023-07-20 pthread_create(3)