pthread_cond_t

条件锁pthread_cond_t

(1)pthread_cond_wait的使用

等待线程
1. 使用pthread_cond_wait前要先加锁
2. pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活
3. pthread_cond_wait被激活后会再自动加锁

(2)pthread_cond_signal的使用

激活线程:
1. 加锁(和等待线程用同一个锁)
2. pthread_cond_signal发送信号
3. 解锁
激活线程的上面三个操作在运行时间上都在等待线程的pthread_cond_wait函数内部。

 

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>struct msg {
        struct msg* next;
        int data;
};
struct msg* tasks = NULL;

pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* TestWait(void* args) {
        pthread_mutex_lock(&mu);//这里开始时加锁
        while(1) {
                pthread_cond_wait(&cond, &mu);//该函数首先将当前线程加入内部的等待列表中,然后释放锁,接着休眠并阻塞。。。。。直到有外部信号(pthread_cond_signal)通知,会加锁然后返回。
                printf("%ld wake up\n", pthread_self());
                if (tasks != NULL) {
                        struct msg* tsk = tasks;
                        tasks = tasks->next;
                        printf("tid:%ld data:%ld\n", pthread_self(), tsk->data);
                        free(tsk);
                }
        }
        pthread_mutex_unlock(&mu);
        pthread_exit(NULL);
}

int main() {

        pthread_t tids[10];
        for(int i = 0; i < 10; i++) {
                pthread_create(&tids[i], NULL, TestWait, NULL);
        }
        sleep(1);

        for (int i = 0; i < 20; i++) {
                pthread_mutex_lock(&mu);

                struct msg* tmp = (struct msg*) malloc(sizeof(struct msg));
                tmp->next = tasks;
                tmp->data = 3;
                tasks = tmp;

                pthread_cond_signal(&cond);
                //pthread_cond_broadcast(&cond);
                pthread_mutex_unlock(&mu);
        }

        pthread_exit(NULL);
        return 0;
}

 

转载于:https://www.cnblogs.com/Dream-Chaser/p/7498097.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值