Linux-条件变量

通信

Posted by MetaNetworks on September 7, 2019
本页面总访问量

条件变量

与互斥变量不同的是,条件变量可以在保证互斥的同时,实现进程之间的同步。(在条件变量等待的情况下,与其绑定的已经加锁的变量仍然可以被其他进程加锁)

  • 子进程调用条件变量等待父进程
  • 父进程做完操作后,调用条件变量,发出信号表明子进程可以继续操作
  • 子进程继续执行

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

pthread_mutex_t count_lock;
pthread_cond_t count_ready;

int count=0;

void *decrement_count(void *arg){
    pthread_mutex_lock(&count_lock);
    printf("decrement:waiting\n");
    pthread_cond_wait(&count_ready, &count_lock);
    /*等待条件变量,期间互斥量仍然可用*/
    count = count - 1;
    printf("decrement:count = %d\n", count);
    pthread_mutex_unlock(&count_lock);
    printf("decrement quit\n");
    pthread_exit(NULL);
}

void *increment_count(void *arg) {
    pthread_mutex_lock(&count_lock);
    printf("increment:running\n");
    count = count + 1;
    pthread_cond_signal(&count_ready);
    /*除法条件变量*/
    printf("increment:count = %d\n", count);
    pthread_mutex_unlock(&count_lock);
    pthread_exit(NULL);
}

int main(){
    pthread_t tid1,tid2;
    count=0;
    pthread_mutex_init(&count_lock, NULL);
    pthread_cond_init(&count_ready, NULL);
    pthread_create(&tid1, NULL, decrement_count, NULL);
    sleep(2);
    pthread_create(&tid2, NULL, increment_count, NULL);
    pthread_join(tid2, NULL);
    printf("decrement quit\n");
    pthread_join(tid1, NULL);
    return 0;
}

效果图:

两个进程,一个进程把值+1后给条件变量发信息,另一个进程接收到后就将值-1

image-20190907175237381