The thread_attr.c program that follows shows some of these attributes in action, with proper conditionalization to avoid using the pthread_exit
, which means that the process will terminate when the last thread exits.
This example does not include the priority scheduling attributes, which are discussed (and demonstrated) in Section 5.5.2. It also does not demonstrate use of the
■ thread_attr.c
1 #include
2 #include
3 #include "errors.h"
4
5 /*
6 * Thread start routine that reports it ran, and then exits.
7 */
8 void *thread_routine (void *arg)
9 {
10 printf ("The thread is here\n");
11 return NULL;
12 }
13
14 int main (int argc, char *argv[])
15 {
16 pthread_t thread_id;
17 pthread_attr_t thread_attr;
18 struct sched_param thread_param;
19 size_t stack_size;
20 int status;
21
22 status = pthread_attr_init (&thread_attr);
23 if (status != 0)
24 err_abort (status, "Create attr");
25
26 /*
27 * Create a detached thread.
28 */
29 status = pthread_attr_setdetachstate (
30 &thread_attr, PTHREAD_CREATE_DETACHED);
31 if (status != 0)
32 err_abort (status, "Set detach");
33 #ifdef _POSIX_THREAD_ATTR_STACKSIZE
34 /*
35 * If supported, determine the default stack size and report
36 * it, and then select a stack size for the new thread.
37 *
38 * Note that the standard does not specify the default stack
39 * size, and the default value in an attributes object need
40 * not be the size that will actually be used. Solaris 2.5
41 * uses a value of 0 to indicate the default.
42 */
43 status = pthread_attr_getstacksize (&thread_attr, &stack_size);
44 if (status != 0)
45 err_abort (status, "Get stack size");
46 printf ("Default stack size is %u; minimum is %u\n",
47 stack_size, PTHREAD_STACK_MIN);
48 status = pthread_attr_setstacksize (
49 &thread_attr, PTHREAD_STACK_MIN*2);
50 if (status != 0)
51 err_abort (status, "Set stack size");
52 #endif
53 status = pthread_create (
54 &thread_id, &thread_attr, thread_routine, NULL);
55 if (status != 0)
56 err_abort (status, "Create thread");
57 printf ("Main exiting\n");
58 pthread_exit (NULL);
59 return 0;
60 }
5.3 Cancellation
"Now, I give you fair warning,"
shouted the Queen, stamping on the ground as she spoke;
"either you or your head must be off,
and that in about halfno time! Take your choice!"
The Duchess took her choice, and was gone in a moment.