标签:
/*
* This demo shows how to 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);
}
标签:
原文地址:http://www.cnblogs.com/qingxueyunfeng/p/4711203.html