2 #include "errors.h"
3
4 pthread_once_t once_block = PTHREAD_ONCE_INIT;
5 pthread_mutex_t mutex;
6
7 /*
8 * This is the one-time initialization routine. It will be
9 * called exactly once, no matter how many calls to pthread_once
10 * with the same control structure are made during the course of
11 * the program.
12 */
13 void once_init_routine (void)
14 {
15 int status;
16
17 status = pthread_mutex_init (&mutex, NULL);
18 if (status != 0)
19 err_abort (status, "Init Mutex");
20 }
21
22 /*
23 * Thread start routine that calls pthread_once.
24 */
25 void *thread_routine (void *arg)
26 {
27 int status;
28
29 status = pthread_once (&once_block, once_init_routine);
30 if (status != 0)
31 err_abort (status, "Once init");
32 status = pthread_mutex_lock (&mutex);
33 if (status != 0)
34 err_abort (status, "Lock mutex");
35 printf ("thread_routine has locked the mutex.\n");
36 status = pthread_mutex_unlock (&mutex);
37 if (status != 0)
38 err_abort (status, "Unlock mutex");
39 return NULL;
40 }
41
42 int main (int argc, char *argv[])
43 {
44 pthread_t thread_id;
45 char *input, buffer[64];
46 int status;
47
48 status = pthread_create (&thread_id, NULL, thread_routine, NULL);
49 if (status != 0)
50 err_abort (status, "Create thread");
51 status = pthread_once (&once_block, once_init_routine);
52 if (status != 0)
53 err_abort (status, "Once init");
54 status = pthread_mutex_lock (&mutex);
55 if (status != 0)
56 err_abort (status, "Lock mutex");
57 printf ("Main has locked the mutex.\n");
58 status = pthread_mutex_unlock (&mutex);
59 if (status != 0)
60 err_abort (status, "Unlock mutex");
61 status = pthread_join (thread_id, NULL);
62 if (status != 0)
63 err_abort (status, "Join thread");
64 return 0;
65 }
5.2 Attributes objects
The fifth ls ambition. It next will be right
To describe each particular batch:
Distinguishing those that have feathers, and bite,
From those that have whiskers, and scratch.
So far, when we created threads, or dynamically initialized mutexes and condition variables, we have usually used the pointer value NULL as the second argument. That argument is actually a pointer to an
An attributes object is an extended argument list provided when you initialize an object. It allows the main interfaces (for example, pthread_create
) to be relatively simple, while allowing "expert" capability when you need it. Later POSIX standards will be able to add options without requiring source changes to existing code. In addition to standard attributes provided by Pthreads, an implementation can provide specialized options without creating nonstandard parameters.