码迷,mamicode.com
首页 > 系统相关 > 详细

Linux IPC(mutex & cond)

时间:2015-08-07 18:55:35      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * 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);
}




Linux IPC(mutex & cond)

标签:

原文地址:http://www.cnblogs.com/qingxueyunfeng/p/4711203.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!