Multi-Thread----Condition Variables

等待条件有两种方式:无条件等待pthread_cond_wait()和计时等待pthread_cond_timedwait()

激发条件有两种形式:pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;而pthread_cond_broadcast()则激活所有等待线程

在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。

在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应

用互斥量锁住条件,防止同一个条件被多个线程竞争.

下面例子是创建三个线程,设定全局变量i,当i==1时唤醒线程1,当i==2时唤醒线程2,当i==3时唤醒线程3.

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

int i = -1;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;

void thread1() {

    printf("Therad1 Begin\n");

    pthread_mutex_lock(&mutex);
    while (i != 1) {
        printf("Therad1 Waiting\n");
        pthread_cond_wait(&condition, &mutex);
    }

    printf("Thread1 doing\n");

    pthread_mutex_unlock(&mutex);

    printf("Thread1 End\n");
}

void thread2() {

    printf("Therad2 Begin\n");

    pthread_mutex_lock(&mutex);
    while (i != 2) {
        printf("Therad2 Waiting\n");
        pthread_cond_wait(&condition, &mutex);
    }

    printf("Thread2 doing\n");

    pthread_mutex_unlock(&mutex);

    printf("Thread2 End\n");
}

void thread3() {

    printf("Therad3 Begin\n");

    pthread_mutex_lock(&mutex);
    while (i != 3) {
        printf("Therad3 Waiting\n");
        pthread_cond_wait(&condition, &mutex);
    }

    printf("Thread3 doing\n");

    pthread_mutex_unlock(&mutex);

    printf("Thread3 End\n");
}

int main(int argc, const char * argv[]) {

    pthread_t tid1;
    pthread_t tid2;
    pthread_t tid3;
    void *t1 = thread1;
    void *t2 = thread2;
    void *t3 = thread3;

    pthread_create(&tid1, NULL, t1, NULL);
    pthread_create(&tid2, NULL, t2, NULL);
    pthread_create(&tid3, NULL, t3, NULL);

    while (i != 3) {
        i++;
        printf("i = %d\n",i);
        sleep(3);
        pthread_cond_broadcast(&condition);
    }

    return 0;
}

输出结果:

i = 0
Therad1 Begin
Therad1 Waiting
Therad3 Begin
Therad2 Begin
Therad3 Waiting
Therad2 Waiting
i = 1
Thread1 doing
Thread1 End
Therad3 Waiting
Therad2 Waiting
i = 2
Therad3 Waiting
Thread2 doing
Thread2 End
i = 3
Thread3 doing
Thread3 End

总结:条件不满足时,线程挂起,等待条件满足.

因为使用的pthread_cond_broadcast,所以使用while循环判断条件是否成立.

当没有用互斥量锁住条件时:

i = 0
Therad3 Begin
Therad1 Begin
Therad2 Begin
Therad3 Waiting
Therad1 Waiting
Therad2 Waiting
i = 1
Therad3 Waiting
Therad2 Waiting
Thread1 doing
Thread1 End
i = 2
i = 3//////////////或者/////////////i = 0Therad1 BeginTherad3 BeginTherad2 BeginTherad1 WaitingTherad3 WaitingTherad2 Waitingi = 1Thread1 doingThread1 Endi = 2i = 3
时间: 2024-11-03 22:09:20

Multi-Thread----Condition Variables的相关文章

使用Condition Variables 实现一个线程安全队列

使用Condition Variables实现一个线程安全队列 多线程代码需要面对的一个问题和是如何把数据从一个县城传到另一个县城. 举个栗子,一个常见的是把串行算法并行化方法是,把他们分成块并且做成一个管道.管道中任意一块都可以单独在一个线程里运行.每个阶段完成后添加数据到输入队列给下个阶段. Basic Thread Safety with a Mutex 使用mutex实现简单的线程安全 最简单的办法是封装一个非线程安全的队列,使用mutex保护它(实例使用boost中的方法和类型,需要1

Condition Variables

Condition variables are synchronization primitives that enable threads to wait until a particular condition occurs. Condition variables are user-mode objects that cannot be shared across processes. Condition variables enable threads to atomically rel

并行编程之条件变量(posix condition variables)

在整理Java LockSupport.park()的东东,看到了个"Spurious wakeup",重新梳理下. 首先来个<UNIX环境高级编程>里的例子: [cpp] view plaincopy #include <pthread.h> struct msg { struct msg *m_next; /* ... more stuff here ... */ }; struct msg *workq; pthread_cond_t qready = P

深入解析条件变量(condition variables)

深入解析条件变量 什么是条件变量(condition variables) 引用APUE中的一句话: Condition variables are another synchronization mechanism available to threads. These synchronization objects provide a place for threads to rendezvous. When used with mutexes, condition variables al

4.锁--并行编程之条件变量(posix condition variables)

在整理Java LockSupport.park()的东东.看到了个"Spurious wakeup".又一次梳理下. 首先来个<UNIX环境高级编程>里的样例: [cpp] view plaincopy #include <pthread.h> struct msg { struct msg *m_next; /* ... more stuff here ... */ }; struct msg *workq; pthread_cond_t qready = 

c++11多线程记录6:条件变量(condition variables)

https://www.youtube.com/watch?v=13dFggo4t_I视频地址 实例1 考虑这样一个场景:存在一个全局队列deque,线程A向deque中推入数据(写),线程B从deque中取出数据(读). deque这个资源对象就需要用mutex做访问控制,代码如下: std::deque<int> q; std::mutex mu; void func1() { int ct = 10; while (ct > 0) { std::unique_lock<std

multi thread for Java

I try to do a testing for HashTable Sychronized behavior today. As an Sychronized Object, HashTable already an Sychronized at put and get function. I wanna to know more about the iterator behaviors on multi-threading. 1 package leetcode; 2 3 import j

Multi account chang login with multi -thread

void worker_DoWork(object sender, DoWorkEventArgs e) { isBussy = true; if (Common.isChangingAccount) { rt = new ResultInfo() { code = 3, isSucc = false, msg = "now system change account" }; return; } if (isTest) { rt = new ResultInfo() { code=1,

posix thread介绍

 posix thread是操作系统级(OS level)的API规范,主要用来定义线程及线程间同步的相关操作,采用C语言定义.posix规范主要在unix like类系统上实现:Windows类系统采用了自己的线程API.目前很多语言都在其标准库中提供了语言级的线程支持:如Java中的Thread,concurrenty包:python中的threading model:C++11标准中的thread库等.还有很多以第三方库方式提供的各种语言的线程实现,就不一一列举了. 线程环境要素 定义

Boost::thread库的使用

阅读对象 本文假设读者有几下Skills [1]在C++中至少使用过一种多线程开发库,有Mutex和Lock的概念. [2]熟悉C++开发,在开发工具中,能够编译.设置boost::thread库. 环境 [1]Visual Studio 2005/2008 with SP1 [2]boost1.39/1.40 概要 通过实例介绍boost thread的使用方式,本文主要由线程启动.Interruption机制.线程同步.等待线程退出.Thread Group几个部份组成. 正文 线程启动 线