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
85 attributes(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
109 detached is useful for some types of daemon threads whose exit status
110 the application does not need to care about. By default, a new thread
111 is created in a joinable state, unless attr was set to create the
112 thread in a detached state (using pthread_attr_setdetachstate(3)).
113
114 On Linux/x86-32, the default stack size for a new thread is 2
115 megabytes. Under the NPTL threading implementation, if the
116 RLIMIT_STACK soft resource limit at the time the program started has
117 any value other than "unlimited", then it determines the default stack
118 size of new threads. Using pthread_attr_setstacksize(3), the stack
119 size attribute can be explicitly set in the attr argument used to cre‐
120 ate a thread, in order to obtain a stack size other than the default.
121
123 In the obsolete LinuxThreads implementation, each of the threads in a
124 process has a different process ID. This is in violation of the POSIX
125 threads specification, and is the source of many other nonconformances
126 to the standard; see pthreads(7).
127
129 The program below demonstrates the use of pthread_create(), as well as
130 a number of other functions in the pthreads API.
131
132 In the following run, on a system providing the NPTL threading imple‐
133 mentation, the stack size defaults to the value given by the "stack
134 size" resource limit:
135
136 $ ulimit -s
137 8192 # The stack size limit is 8 MB (0x800000 bytes)
138 $ ./a.out hola salut servus
139 Thread 1: top of stack near 0xb7dd03b8; argv_string=hola
140 Thread 2: top of stack near 0xb75cf3b8; argv_string=salut
141 Thread 3: top of stack near 0xb6dce3b8; argv_string=servus
142 Joined with thread 1; returned value was HOLA
143 Joined with thread 2; returned value was SALUT
144 Joined with thread 3; returned value was SERVUS
145
146 In the next run, the program explicitly sets a stack size of 1 MB
147 (using pthread_attr_setstacksize(3)) for the created threads:
148
149 $ ./a.out -s 0x100000 hola salut servus
150 Thread 1: top of stack near 0xb7d723b8; argv_string=hola
151 Thread 2: top of stack near 0xb7c713b8; argv_string=salut
152 Thread 3: top of stack near 0xb7b703b8; argv_string=servus
153 Joined with thread 1; returned value was HOLA
154 Joined with thread 2; returned value was SALUT
155 Joined with thread 3; returned value was SERVUS
156
157 Program source
158
159 #include <pthread.h>
160 #include <string.h>
161 #include <stdio.h>
162 #include <stdlib.h>
163 #include <unistd.h>
164 #include <errno.h>
165 #include <ctype.h>
166
167 #define handle_error_en(en, msg) \
168 do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
169
170 #define handle_error(msg) \
171 do { perror(msg); exit(EXIT_FAILURE); } while (0)
172
173 struct thread_info { /* Used as argument to thread_start() */
174 pthread_t thread_id; /* ID returned by pthread_create() */
175 int thread_num; /* Application-defined thread # */
176 char *argv_string; /* From command-line argument */
177 };
178
179 /* Thread start function: display address near top of our stack,
180 and return upper-cased copy of argv_string */
181
182 static void *
183 thread_start(void *arg)
184 {
185 struct thread_info *tinfo = arg;
186 char *uargv, *p;
187
188 printf("Thread %d: top of stack near %p; argv_string=%s\n",
189 tinfo->thread_num, &p, tinfo->argv_string);
190
191 uargv = strdup(tinfo->argv_string);
192 if (uargv == NULL)
193 handle_error("strdup");
194
195 for (p = uargv; *p != '\0'; p++)
196 *p = toupper(*p);
197
198 return uargv;
199 }
200
201 int
202 main(int argc, char *argv[])
203 {
204 int s, tnum, opt, num_threads;
205 struct thread_info *tinfo;
206 pthread_attr_t attr;
207 int stack_size;
208 void *res;
209
210 /* The "-s" option specifies a stack size for our threads */
211
212 stack_size = -1;
213 while ((opt = getopt(argc, argv, "s:")) != -1) {
214 switch (opt) {
215 case 's':
216 stack_size = strtoul(optarg, NULL, 0);
217 break;
218
219 default:
220 fprintf(stderr, "Usage: %s [-s stack-size] arg...\n",
221 argv[0]);
222 exit(EXIT_FAILURE);
223 }
224 }
225
226 num_threads = argc - optind;
227
228 /* Initialize thread creation attributes */
229
230 s = pthread_attr_init(&attr);
231 if (s != 0)
232 handle_error_en(s, "pthread_attr_init");
233
234 if (stack_size > 0) {
235 s = pthread_attr_setstacksize(&attr, stack_size);
236 if (s != 0)
237 handle_error_en(s, "pthread_attr_setstacksize");
238 }
239
240 /* Allocate memory for pthread_create() arguments */
241
242 tinfo = calloc(num_threads, sizeof(struct thread_info));
243 if (tinfo == NULL)
244 handle_error("calloc");
245
246 /* Create one thread for each command-line argument */
247
248 for (tnum = 0; tnum < num_threads; tnum++) {
249 tinfo[tnum].thread_num = tnum + 1;
250 tinfo[tnum].argv_string = argv[optind + tnum];
251
252 /* The pthread_create() call stores the thread ID into
253 corresponding element of tinfo[] */
254
255 s = pthread_create(&tinfo[tnum].thread_id, &attr,
256 &thread_start, &tinfo[tnum]);
257 if (s != 0)
258 handle_error_en(s, "pthread_create");
259 }
260
261 /* Destroy the thread attributes object, since it is no
262 longer needed */
263
264 s = pthread_attr_destroy(&attr);
265 if (s != 0)
266 handle_error_en(s, "pthread_attr_destroy");
267
268 /* Now join with each thread, and display its returned value */
269
270 for (tnum = 0; tnum < num_threads; tnum++) {
271 s = pthread_join(tinfo[tnum].thread_id, &res);
272 if (s != 0)
273 handle_error_en(s, "pthread_join");
274
275 printf("Joined with thread %d; returned value was %s\n",
276 tinfo[tnum].thread_num, (char *) res);
277 free(res); /* Free memory allocated by thread */
278 }
279
280 free(tinfo);
281 exit(EXIT_SUCCESS);
282 }
283
285 getrlimit(2), pthread_attr_init(3), pthread_cancel(3),
286 pthread_detach(3), pthread_equal(3), pthread_exit(3),
287 pthread_getattr_np(3), pthread_join(3), pthread_self(3),
288 pthread_setattr_default_np(3), pthreads(7)
289
291 This page is part of release 4.15 of the Linux man-pages project. A
292 description of the project, information about reporting bugs, and the
293 latest version of this page, can be found at
294 https://www.kernel.org/doc/man-pages/.
295
296
297
298Linux 2017-09-15 PTHREAD_CREATE(3)