C++多线程条件变量实战

一 条件变量相关函数

 

操作

相关函数说明

初始化条件变量

pthread_cond_init 语法

基于条件变量阻塞

pthread_cond_wait 语法

解除阻塞特定线程

pthread_cond_signal 语法

在指定的时间之前阻塞

pthread_cond_timedwait 语法

在指定的时间间隔内阻塞

pthread_cond_reltimedwait_np 语法

解除阻塞所有线程

pthread_cond_broadcast 语法

销毁条件变量状态

pthread_cond_destroy 语法

二 代码

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

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;/*初始化互斥锁*/
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;/*初始化条件变量*/

void *thread1(void *);
void *thread2(void *);

int i = 1;
int main(void)
{
    pthread_t t_a;
    pthread_t t_b;

    pthread_create(&t_a, NULL, thread2, (void *)NULL);//创建线程t_a
    pthread_create(&t_b, NULL, thread1, (void *)NULL); //创建线程t_b
    pthread_join(t_b, NULL);/*等待进程t_b结束*/
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    exit(0);
}

void *thread1(void *junk)
{
    for (i = 1; i <= 20; i++)
    {
        pthread_mutex_lock(&mutex);//锁住互斥量
        if (i % 3 == 0)
            pthread_cond_signal(&cond); //唤醒等待条件变量cond的线程
        else       
            printf("thead1:%d\n", i); //打印不能整除3的i
        pthread_mutex_unlock(&mutex);//解锁互斥量

        sleep(1);
    }

}

void *thread2(void *junk)
{
    while (i < 20)
    {
        pthread_mutex_lock(&mutex);

        if (i % 3 != 0)
            //调用该函数前,必须对mutex加锁
            //调用该函数后,会执行下面原子操作(1 线程被条件变量cond阻塞。2 线程将mutex解锁)
            pthread_cond_wait(&cond, &mutex);//等待条件变量
            //该函数返回要满足两个条件(1 等到thread1线程发来的cond变量的信号 2 mutex被thread1线程解锁)
        printf("------------thread2:%d\n", i); //打印能整除3的i
        pthread_mutex_unlock(&mutex);

        sleep(2);   //休眠2秒是为了打印3的倍数后,然线程1先执行
    }

}

三 运行

[root@localhost test]# g++ -o test test.cpp -lpthread
[root@localhost test]# ./test
thead1:1
thead1:2
------------thread2:3
thead1:4
thead1:5
------------thread2:6
thead1:7
thead1:8
------------thread2:9
thead1:10
thead1:11
------------thread2:12
thead1:13
thead1:14
------------thread2:15
thead1:16
thead1:17
------------thread2:18
thead1:19
thead1:20

四 说明

线程1在累加i的过程中,如果发现i能整除3,就唤醒等待条件变量cond的线程。

线程2在循环过程中,如果i不能被3整除,则阻塞线程,等待条件变量。

由于pthread_cond_wait需要释放锁,因此当调用pthread_cond_wait的时候,mutex必须被线程锁定,由pthread_mutex_lock(&mutex);这一行代码完成。

pthread_cond_wait收到条件变量信号时,要对mutex加锁,因此thread1中pthread_cond_signal后面的锁解后,才会让thread2中的pthread_cond_wait返回,并执行后面的语句。并且会对mutex上锁,用完i的时候,再对mutex解锁。这样可以让线程1继续执行。

当线程1打印了一个非被3整除的i后,就休眠(sleep)了,此时将切换到线程2执行,线程2如果发现i不能整除3,就阻塞。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值