54 * value increments each element in the shared array.
55 */
56 if (status == -1) {
57 int thread_num;
58
59 for (thread_num = 0; thread_num < THREADS; thread_num++)
60 thread[thread_num].increment += 1;
61 }
62 }
63 return NULL;
64 }
65
66 int main (int arg, char *argv[])
67 {
68 int thread_count, array_count;
69 int status;
70
71 barrier_init (&barrier, THREADS);
72
73 /*
74 * Create a set of threads that will use the barrier.
75 */
76 for (thread_count = 0; thread_count < THREADS; thread_count++) { 7 7 thread[thread_count].increment = thread_count;
78 thread[thread_count].number = thread_count;
79
80 for (array_count = 0; array_count < ARRAY; array_count++)
81 thread[thread_count].array[array_count] = array_count + 1;
82
83 status = pthread_create (&thread[thread_count].thread_id,
84 NULL, thread_routine, (void*)&thread[thread_count]);
85 if (status != 0)
86 err_abort (status, "Create thread");
87 }
88
89 /*
90 * Now join with each of the threads.
91 */
92 for (thread_count = 0; thread_count < THREADS; thread_count++) {
93 status = pthread_join (thread[thread_count].thread_id, NULL);
94 if (status != 0)
95 err_abort (status, "Join thread");
96
97 printf ("%02d: (%d) ",
98 thread_count, thread[thread_count].increment);
99
100 for (array_count = 0; array_count < ARRAY; array_count++)
101 printf ("%010u ",
102 thread[thread_count].array[array_count]);
103 printf ("\n");
104 }
105
106 /*
107 * To be thorough, destroy the barrier.
108 */
109 barrier_destroy (&barrier);
110 return 0;
111 }
7.1.2 Read/write locks
A read/write lock is a lot like a mutex. It is another way to prevent more than one thread from modifying shared data at the same time. But unlike a mutex it distinguishes between
Read/write locks are used to protect information that you need to read frequently but usually don't need to modify. For example, when you build a cache of recently accessed information, many threads may simultaneously examine the cache without conflict. When a thread needs to update the cache, it must have exclusive access.
When a thread locks a read/write lock, it chooses
When both readers and writers are waiting for access at the same time, the readers are given precedence when the write lock is released.