多线程_条件变量pthread_cond_t

本文详细介绍了POSIX线程中条件变量的使用方法,包括创建、等待、唤醒及销毁等操作,并通过一个具体的C语言示例展示了如何利用条件变量实现线程间的同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需包含头文件 pthread.h

1.创建条件变量

pthread_cond_init(pthread_cond_t *, const pthread_condattr_t *);

参数说明:
pthread_cond_t * 声明方式 pthread_cond_t conA;
pthread_condattr_t *条件变量属性。

2.阻塞以等待一个信号

pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *);

描述:阻塞调用改函数的线程,直到通过pthread_cond_t *参数被唤醒。
参数说明:
pthread_cond_t * 条件变量的唯一ID。
pthread_mutex_t * 互斥锁。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。防止条件变量未被阻塞而先被唤醒。

3.唤醒线程

pthread_cond_signal(pthread_cond_t *);
描述:唤醒pthread_cond_t *所指向的条件变量所阻塞住的线程。

pthread_cond_broadcast(pthread_cond_t *);
描述:唤醒多个被pthread_cond_t *所指向的条件变量所阻塞住的线程。

4.销毁条件变量

pthread_cond_destroy(pthread_cond_t *);

5.示例

#include <iostream>
#include <pthread.h>
#include <unistd.h>
pthread_t A;
pthread_t B;
pthread_cond_t con;
pthread_mutex_t m;

void* ThreadA(void* args);
void* ThreadB(void* args);

int main(int argc, const char * argv[]) {
    pthread_mutex_init(&m, NULL);
    pthread_cond_init(&con, NULL);//初始化条件变量

    pthread_create(&A, NULL, ThreadA, NULL);
    pthread_create(&B, NULL, ThreadB, NULL);
    pthread_join(A, NULL);
    pthread_join(B, NULL);
    pthread_cond_destroy(&con); //销毁条件变量
    pthread_exit( NULL );
}
void* ThreadA(void* args){
    pthread_mutex_lock(&m);
    for (int j = 0 ; j<10; j++) {
        if(j ==5){
            pthread_cond_wait(&con, &m);//使用条件变量阻塞线程A,等待被唤醒
        }
        printf("%d\n",j);
    }
    pthread_mutex_unlock(&m);
    return NULL;
}
void* ThreadB(void* args){
    pthread_mutex_lock(&m);
    for (int j = 20 ; j<30; j++) {
        if (j==25) {
/*1*/       pthread_cond_signal(&con);//唤醒con条件变量所阻塞的线程:A
        }
        printf("%d\n",j);
    }
    pthread_mutex_unlock(&m);
    return NULL;
}

输出
0
1
2
3
4
20
21
22
23
24
25
26
27
28
29
5
6
7
8
9

若将/*1*/注释则输出:

0
1
2
3
4
20
21
22
23
24
25
26
27
28
29

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值