Debian Codegraph @

listings/chapter-4/spin-condvar.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <pthread.h>
8
9 extern void do_work ();
10
11 int thread_flag;
12 pthread_mutex_t thread_flag_mutex;
13
14 void initialize_flag ()
15 {
16 pthread_mutex_init (&thread_flag_mutex, NULL);
17 thread_flag = 0;
18 }
19
20 /* Calls do_work repeatedly while the thread flag is set; otherwise
21 spins. */
22
23 void* thread_function (void* thread_arg)
24 {
25 while (1) {
26 int flag_is_set;
27
28 /* Protect the flag with a mutex lock. */
29 pthread_mutex_lock (&thread_flag_mutex);
30 flag_is_set = thread_flag;
31 pthread_mutex_unlock (&thread_flag_mutex);
32
33 if (flag_is_set)
34 do_work ();
35 /* Else don't do anything. Just loop again. */
36 }
37 return NULL;
38 }
39
40 /* Sets the value of the thread flag to FLAG_VALUE. */
41
42 void set_thread_flag (int flag_value)
43 {
44 /* Protect the flag with a mutex lock. */
45 pthread_mutex_lock (&thread_flag_mutex);
46 thread_flag = flag_value;
47 pthread_mutex_unlock (&thread_flag_mutex);
48 }