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

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

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


#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
    评论
在C++中,可以使用互斥量(mutex)来实现全局变量的线程同步。互斥量是一种同步原语,用于保护共享资源不被多个线程访问。当一个线程获得了互斥量的锁,其他线程需要等待该线程释放锁才能继续执行。这样可以确保同一刻只有一个线程可以访问共享资源。 在引用的代码示例中,可以看到使用了互斥量来保护全局变量tickets的访问。通过在fun1Proc和fun2Proc函数中使用std::mutex类创建互斥量对象,并使用lock()和unlock()函数来锁定和释放互斥量的锁。这样可以确保在每次访问tickets只有一个线程可以执行,从而避免了数据竞争和不确定的结果。 此外,可以使用条件变量(condition variable)来实现线程之间的通信和同步。条件变量是一种同步原语,用于在多个线程之间进行等待和唤醒操作。当一个线程需要等待某个条件满足,可以调用wait()函数将自己阻塞,直到其他线程通过notify_one()或notify_all()函数唤醒它。这样可以有效地控制线程的执行顺序和同步。 在引用的代码示例中,没有使用条件变量,而是通过循环判断tickets的值来判断是否继续执行。这种方式并不是最优雅和高效的线程同步方法,因为它会造成不必要的CPU资源浪费。使用条件变量可以更好地实现线程之间的同步和通信,提高程序的性能和可维护性。 总结起来,C++中可以使用互斥量和条件变量来实现全局变量的线程同步。互斥量用于保护共享资源的访问,条件变量用于线程之间的等待和唤醒操作。通过合理地运用这些同步原语,可以确保多线程程序的正确性和可靠性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [C++多线程线程同步问题](https://blog.csdn.net/sinat_41928334/article/details/107880741)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值