运用条件变量保持线程同步

线程同步手段:互斥锁,读写锁,条件变量。

本文实例利用条件变量保持读写同步


#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//#define THREAD_SYNC_PROTECT

struct msg {
    struct msg *m_next;
    char context[100];
};

struct msg *workq = NULL;
int flag = 1;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;

void process_msg(void)
{
    struct msg *mp = NULL;

    for (;;) {
#if defined THREAD_SYNC_PROTECT
        /* protect condition varialbe without missing any condition change */
        pthread_mutex_lock(&qlock);
        while (workq == NULL) {
            /* append thread to wait queue and make thread sleep, finally unlock mutex */
            pthread_cond_wait(&qready, &qlock);
            /* relock mutex when function "pthread_cond_wait" returns */
            printf("condition match!\n");
        }
#endif
        if (workq != NULL) {
            mp = workq;
            workq = mp->m_next;
        }

#if defined THREAD_SYNC_PROTECT
        pthread_mutex_unlock(&qlock);
#endif
        if (workq != NULL) {
            /* process message */
            printf("thread %u :receive message %s\n", pthread_self(), mp->context);
            free(mp);
        }
    }
}

void enqueue_msg(struct msg *mp)
{
    /* Get right to operate queue */
    pthread_mutex_lock(&qlock);
    mp->m_next = workq;
    workq = mp;
    pthread_mutex_unlock(&qlock);
    pthread_cond_signal(&qready);
}

void send_msg(void)
{
    int i;

    for (i = 0; i < 10; i++) {
        struct msg *mp = malloc(sizeof(struct msg));
        if (NULL == mp) {
            printf("malloc failed!\n");
            break;
        }

        sprintf(mp->context, "%s[%d] request", "customer", i);
        enqueue_msg(mp);
        sleep(1);
    }
    flag = 0;
}

int main(void)
{

    pthread_t tid_send, tid_process1, tid_process2;
    int ret ;

    pthread_mutex_init(&qlock, NULL);
    ret = pthread_create(&tid_process2, NULL, process_msg, NULL);
    if (ret != 0) {
        printf("create pthread send_msg failed!\n");
        return -1;
    }

    ret = pthread_create(&tid_process1, NULL, process_msg, NULL);
    if (ret != 0) {
        printf("create pthread send_msg failed!\n");
        return -1;
    }

    ret = pthread_create(&tid_send, NULL, send_msg, NULL);
    if (ret != 0) {
        printf("create pthread send_msg failed!\n");
        return -1;
    }
    while(flag);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值