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