/*
* This demo shows the use semaphore between threads.
*
*/
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
/*
* Global shared Resource
*/
struct Shared_resouce {
int global_count;
pthread_mutex_t Mutex;
pthread_cond_t cond;
} shr_res;
void Mutex_clean (void *mutex)
{
Pthread_mutex_unlock ((pthread_mutex_t*) mutex);
}
void* thread_fun (void *arg)
{
printf ("Thread:%ld active.\n", pthread_self ());
while (1)
{
Pthread_mutex_lock (&shr_res.mutex);
while (shr_res.global_count <= 0)
{
Pthread_cond_wait (&shr_res.cond, &shr_res.mutex);
}
shr_res.global_count--;
printf ("Thread%d decrease Globar var.\n", pthread_self ());
Pthread_mutex_unlock (&shr_res.mutex);
Sleep (2);
}
}
int main (int argc, char **argv)
{
pthread_t Id1, Id2;
/*
* Initialize globar var
*/
Shr_res.global_count = 0;
if (Pthread_mutex_init (&shr_res.mutex, NULL)! = 0)
{
printf ("Initialize mutex error!");
Exit (-1);
}
if (Pthread_cond_init (&shr_res.cond, NULL)! = 0)
{
printf ("Initialize condation var error!");
Exit (-1);
}
Pthread_create (&ID1, NULL, thread_fun, NULL);
Pthread_create (&id2, NULL, thread_fun, NULL);
/*
* In main thread, loop of increasing shr_res.global_count.
*/
while (1)
{
Pthread_mutex_lock (&shr_res.mutex);
printf ("Main Thread increase global var.\n");
shr_res.global_count++;
if (Shr_res.global_count > 0)
{
Pthread_cond_signal (&shr_res.cond);
}
Pthread_mutex_unlock (&shr_res.mutex);
Sleep (3);
}
Pthread_join (ID1, NULL);
Pthread_join (Id2, NULL);
Pthread_cond_destroy (&shr_res.cond);
Pthread_mutex_destroy (&shr_res.mutex);
Exit (0);
}
Linux IPC (Mutex & cond)