| 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_cond_t thread_flag_cv; |
| 13 |
pthread_mutex_t thread_flag_mutex; |
| 14 |
|
| 15 |
void initialize_flag () |
| 16 |
{ |
| 17 |
/* Initialize the mutex and condition variable. */ |
| 18 |
pthread_mutex_init (&thread_flag_mutex, NULL); |
| 19 |
pthread_cond_init (&thread_flag_cv, NULL); |
| 20 |
/* Initialize the flag value. */ |
| 21 |
thread_flag = 0; |
| 22 |
} |
| 23 |
|
| 24 |
/* Calls do_work repeatedly while the thread flag is set; blocks if |
| 25 |
the flag is clear. */ |
| 26 |
|
| 27 |
void* thread_function (void* thread_arg) |
| 28 |
{ |
| 29 |
/* Loop infinitely. */ |
| 30 |
while (1) { |
| 31 |
/* Lock the mutex before accessing the flag value. */ |
| 32 |
pthread_mutex_lock (&thread_flag_mutex); |
| 33 |
while (!thread_flag) |
| 34 |
/* The flag is clear. Wait for a signal on the condition |
| 35 |
variable, indicating the flag value has changed. When the |
| 36 |
signal arrives and this thread unblocks, loop and check the |
| 37 |
flag again. */ |
| 38 |
pthread_cond_wait (&thread_flag_cv, &thread_flag_mutex); |
| 39 |
/* When we've gotten here, we know the flag must be set. Unlock |
| 40 |
the mutex. */ |
| 41 |
pthread_mutex_unlock (&thread_flag_mutex); |
| 42 |
/* Do some work. */ |
| 43 |
do_work (); |
| 44 |
} |
| 45 |
return NULL; |
| 46 |
} |
| 47 |
|
| 48 |
/* Sets the value of the thread flag to FLAG_VALUE. */ |
| 49 |
|
| 50 |
void set_thread_flag (int flag_value) |
| 51 |
{ |
| 52 |
/* Lock the mutex before accessing the flag value. */ |
| 53 |
pthread_mutex_lock (&thread_flag_mutex); |
| 54 |
/* Set the flag value, and then signal in case thread_function is |
| 55 |
blocked, waiting for the flag to become set. However, |
| 56 |
thread_function can't actually check the flag until the mutex is |
| 57 |
unlocked. */ |
| 58 |
thread_flag = flag_value; |
| 59 |
pthread_cond_signal (&thread_flag_cv); |
| 60 |
/* Unlock the mutex. */ |
| 61 |
pthread_mutex_unlock (&thread_flag_mutex); |
| 62 |
} |