1PTHREAD_CREATE(3)          Linux Programmer's Manual         PTHREAD_CREATE(3)
2
3
4

NAME

6       pthread_create - create a new thread
7

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

63       On  success,  pthread_create() returns 0; on error, it returns an error
64       number, and the contents of *thread are undefined.
65

ERRORS

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

ATTRIBUTES

84       For  an  explanation  of  the  terms  used   in   this   section,   see
85       attributes(7).
86
87       ┌─────────────────┬───────────────┬─────────┐
88Interface        Attribute     Value   
89       ├─────────────────┼───────────────┼─────────┤
90pthread_create() │ Thread safety │ MT-Safe │
91       └─────────────────┴───────────────┴─────────┘
92

CONFORMING TO

94       POSIX.1-2001, POSIX.1-2008.
95

NOTES

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       Under the NPTL  threading  implementation,  if  the  RLIMIT_STACK  soft
115       resource 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
118       explicitly set in the attr argument used to create a thread,  in  order
119       to  obtain  a  stack  size other than the default.  If the RLIMIT_STACK
120       resource 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              ┌─────────────┬────────────────────┐
124Architecture 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              └─────────────┴────────────────────┘

BUGS

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

EXAMPLE

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
165       (using 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, *p;
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 (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, tnum, opt, num_threads;
223           struct thread_info *tinfo;
224           pthread_attr_t attr;
225           int stack_size;
226           void *res;
227
228           /* The "-s" option specifies a stack size for our threads */
229
230           stack_size = -1;
231           while ((opt = getopt(argc, argv, "s:")) != -1) {
232               switch (opt) {
233               case 's':
234                   stack_size = strtoul(optarg, NULL, 0);
235                   break;
236
237               default:
238                   fprintf(stderr, "Usage: %s [-s stack-size] arg...\n",
239                           argv[0]);
240                   exit(EXIT_FAILURE);
241               }
242           }
243
244           num_threads = argc - optind;
245
246           /* Initialize thread creation attributes */
247
248           s = pthread_attr_init(&attr);
249           if (s != 0)
250               handle_error_en(s, "pthread_attr_init");
251
252           if (stack_size > 0) {
253               s = pthread_attr_setstacksize(&attr, stack_size);
254               if (s != 0)
255                   handle_error_en(s, "pthread_attr_setstacksize");
256           }
257
258           /* Allocate memory for pthread_create() arguments */
259
260           tinfo = calloc(num_threads, sizeof(struct thread_info));
261           if (tinfo == NULL)
262               handle_error("calloc");
263
264           /* Create one thread for each command-line argument */
265
266           for (tnum = 0; tnum < num_threads; tnum++) {
267               tinfo[tnum].thread_num = tnum + 1;
268               tinfo[tnum].argv_string = argv[optind + tnum];
269
270               /* The pthread_create() call stores the thread ID into
271                  corresponding element of tinfo[] */
272
273               s = pthread_create(&tinfo[tnum].thread_id, &attr,
274                                  &thread_start, &tinfo[tnum]);
275               if (s != 0)
276                   handle_error_en(s, "pthread_create");
277           }
278
279           /* Destroy the thread attributes object, since it is no
280              longer needed */
281
282           s = pthread_attr_destroy(&attr);
283           if (s != 0)
284               handle_error_en(s, "pthread_attr_destroy");
285
286           /* Now join with each thread, and display its returned value */
287
288           for (tnum = 0; tnum < num_threads; tnum++) {
289               s = pthread_join(tinfo[tnum].thread_id, &res);
290               if (s != 0)
291                   handle_error_en(s, "pthread_join");
292
293               printf("Joined with thread %d; returned value was %s\n",
294                       tinfo[tnum].thread_num, (char *) res);
295               free(res);      /* Free memory allocated by thread */
296           }
297
298           free(tinfo);
299           exit(EXIT_SUCCESS);
300       }
301

SEE ALSO

303       getrlimit(2), pthread_attr_init(3), pthread_cancel(3),
304       pthread_detach(3), pthread_equal(3), pthread_exit(3),
305       pthread_getattr_np(3), pthread_join(3), pthread_self(3),
306       pthread_setattr_default_np(3), pthreads(7)
307

COLOPHON

309       This page is part of release 5.02 of the Linux man-pages project.  A
310       description of the project, information about reporting bugs, and the
311       latest version of this page, can be found at
312       https://www.kernel.org/doc/man-pages/.
313
314
315
316Linux                             2018-04-30                 PTHREAD_CREATE(3)
Impressum