此处将为大家介绍关于C++11并行编程-条件变量(condition_variable)详细说明的详细内容,并且为您解答有关c++条件变量使用的相关问题,此外,我们还将为您介绍关于androidCon
此处将为大家介绍关于C++11并行编程-条件变量(condition_variable)详细说明的详细内容,并且为您解答有关c++条件变量使用的相关问题,此外,我们还将为您介绍关于android ConditionVariable、android.os.ConditionVariable的实例源码、c – std :: condition_variable :: wait_until的实现、c – `std :: condition_variable :: wait_for`经常调用谓词的有用信息。
本文目录一览:- C++11并行编程-条件变量(condition_variable)详细说明(c++条件变量使用)
- android ConditionVariable
- android.os.ConditionVariable的实例源码
- c – std :: condition_variable :: wait_until的实现
- c – `std :: condition_variable :: wait_for`经常调用谓词
C++11并行编程-条件变量(condition_variable)详细说明(c++条件变量使用)
<condition_variable >
头文件主要包含有类和函数相关的条件变量。
包括相关类 std::condition_variable
和 std::condition_variable_any
,还有枚举类型std::cv_status
。另外还包含函数 std::notify_all_at_thread_exit()
,以下分别介绍一下以上几种类型。
std::condition_variable 类介绍
std::condition_variable
是条件变量,很多其它有关条件变量的定义參考维基百科。Linux
下使用 Pthread
库中的 pthread_cond_*()
函数提供了与条件变量相关的功能, Windows
则參考 MSDN
。
当 std::condition_variable
对象的某个wait
函数被调用的时候,它使用 std::unique_lock
(通过 std::mutex
) 来锁住当前线程。
当前线程会一直被堵塞。直到另外一个线程在同样的 std::condition_variable
对象上调用了 notification
函数来唤醒当前线程。
std::condition_variable
对象通常使用 std::unique_lock<std::mutex>
来等待,假设须要使用另外的 lockable
类型,能够使用std::condition_variable_any
类。本文后面会讲到 std::condition_variable_any
的使用方法。
#include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex,std::unique_lock #include <condition_variable> // std::condition_variable std::mutex mtx; // 全局相互排斥锁. std::condition_variable cv; // 全局条件变量. bool ready = false; // 全局标志位. void do_print_id(int id) { std::unique_lock <std::mutex> lck(mtx); while (!ready) // 假设标志位不为 true,则等待... cv.wait(lck); // 当前线程被堵塞,当全局标志位变为 true 之后,// 线程被唤醒,继续往下运行打印线程编号id. std::cout << "thread " << id << ‘\n‘; } void go() { std::unique_lock <std::mutex> lck(mtx); ready = true; // 设置全局标志位为 true. cv.notify_all(); // 唤醒全部线程. } int main() { std::thread threads[10]; // spawn 10 threads: for (int i = 0; i < 10; ++i) threads[i] = std::thread(do_print_id,i); std::cout << "10 threads ready to race...\n"; go(); // go! for (auto & th:threads) th.join(); return 0; }
结果:
10 threads ready to race... thread 1 thread 0 thread 2 thread 3 thread 4 thread 5 thread 6 thread 7 thread 8 thread 9
std::condition_variable
的拷贝构造函数被禁用,仅仅提供了默认构造函数。
看看 std::condition_variable
的各个成员函数
std::condition_variable::wait()
介绍:
std::condition_variable
提供了两种 wait()
函数。
void wait (unique_lock<mutex>& lck); template <class Predicate> void wait (unique_lock<mutex>& lck,Predicate pred);
当前线程调用 wait()
后将被堵塞(此时当前线程应该获得了锁(mutex
),最好还是设获得锁 lck
),直到另外某个线程调用 notify_*
唤醒了当前线程。
在线程被堵塞时,该函数会自己主动调用 lck.unlock()
释放锁,使得其它被堵塞在锁竞争上的线程得以继续运行。另外,一旦当前线程获得通知(notified
,一般是另外某个线程调用 notify_*
唤醒了当前线程),wait()
函数也是自己主动调用 lck.lock()
,使得lck
的状态和 wait
函数被调用时同样。
在另外一种情况下(即设置了 Predicate
)。仅仅有当 pred
条件为false
时调用 wait()
才会堵塞当前线程。而且在收到其它线程的通知后仅仅有当 pred
为 true
时才会被解除堵塞。
因此另外一种情况相似以下代码:
#include <iostream> // std::cout #include <thread> // std::thread,std::this_thread::yield #include <mutex> // std::mutex,std::unique_lock #include <condition_variable> // std::condition_variable std::mutex mtx; std::condition_variable cv; int cargo = 0; bool shipment_available() { return cargo != 0; } // 消费者线程. void consume(int n) { for (int i = 0; i < n; ++i) { std::unique_lock <std::mutex> lck(mtx); cv.wait(lck,shipment_available); std::cout << cargo << ‘\n‘; cargo = 0; } } int main() { std::thread consumer_thread(consume,10); // 消费者线程. // 主线程为生产者线程,生产 10 个物品. for (int i = 0; i < 10; ++i) { while (shipment_available()) std::this_thread::yield(); std::unique_lock <std::mutex> lck(mtx); cargo = i + 1; cv.notify_one(); } consumer_thread.join(); return 0; }
1 2 3 4 5 6 7 8 9 10
std::condition_variable::wait_for() 介绍
template <class Rep,class Period> cv_status wait_for (unique_lock<mutex>& lck,const chrono::duration<Rep,Period>& rel_time); template <class Rep,class Period,class Predicate> bool wait_for (unique_lock<mutex>& lck,Period>& rel_time,Predicate pred);
与std::condition_variable::wait()
相似,只是 wait_for
能够指定一个时间段,在当前线程收到通知或者指定的时间 rel_time
超时之前。该线程都会处于堵塞状态。而一旦超时或者收到了其它线程的通知,wait_for
返回,剩下的处理步骤和 wait()
相似。
另外,wait_for
的重载版本号的最后一个參数pred
表示 wait_for
的预測条件。仅仅有当 pred
条件为false
时调用 wait()
才会堵塞当前线程,而且在收到其它线程的通知后仅仅有当 pred
为 true
时才会被解除堵塞,因此相当于例如以下代码:
return wait_until (lck,chrono::steady_clock::Now() + rel_time,std::move(pred));
请看以下的样例(參考),以下的样例中,主线程等待th
线程输入一个值。然后将th
线程从终端接收的值打印出来。在th
线程接受到值之前,主线程一直等待。每一个一秒超时一次,并打印一个 "."
:
#include <iostream> // std::cout #include <thread> // std::thread #include <chrono> // std::chrono::seconds #include <mutex> // std::mutex,std::unique_lock #include <condition_variable> // std::condition_variable,std::cv_status std::condition_variable cv; int value; void do_read_value() { std::cin >> value; cv.notify_one(); } int main () { std::cout << "Please,enter an integer (I‘ll be printing dots): \n"; std::thread th(do_read_value); std::mutex mtx; std::unique_lock<std::mutex> lck(mtx); while (cv.wait_for(lck,std::chrono::seconds(1)) == std::cv_status::timeout) { std::cout << ‘.‘; std::cout.flush(); } std::cout << "You entered: " << value << ‘\n‘; th.join(); return 0; }
std::condition_variable::wait_until 介绍
template <class Clock,class Duration> cv_status wait_until (unique_lock<mutex>& lck,const chrono::time_point<Clock,Duration>& abs_time); template <class Clock,class Duration,class Predicate> bool wait_until (unique_lock<mutex>& lck,Duration>& abs_time,Predicate pred);
与 std::condition_variable::wait_for
相似,可是wait_until
能够指定一个时间点,在当前线程收到通知或者指定的时间点 abs_time
超时之前,该线程都会处于堵塞状态。而一旦超时或者收到了其它线程的通知,wait_until
返回。剩下的处理步骤和 wait_until()
相似。
另外,wait_until
的重载版本号的最后一个參数 pred
表示 wait_until
的预測条件。仅仅有当 pred
条件为 false
时调用 wait()
才会堵塞当前线程,而且在收到其它线程的通知后仅仅有当pred
为 true
时才会被解除堵塞,因此相当于例如以下代码:
while (!pred()) if ( wait_until(lck,abs_time) == cv_status::timeout) return pred(); return true;
std::condition_variable::notify_one() 介绍
唤醒某个等待(wait
)线程。假设当前没有等待线程,则该函数什么也不做,假设同一时候存在多个等待线程,则唤醒某个线程是不确定的(unspecified)
。
请看下例(參考):
#include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex,std::unique_lock #include <condition_variable> // std::condition_variable std::mutex mtx; std::condition_variable cv; int cargo = 0; // shared value by producers and consumers void consumer() { std::unique_lock < std::mutex > lck(mtx); while (cargo == 0) cv.wait(lck); std::cout << cargo << ‘\n‘; cargo = 0; } void producer(int id) { std::unique_lock < std::mutex > lck(mtx); cargo = id; cv.notify_one(); } int main() { std::thread consumers[10],producers[10]; // spawn 10 consumers and 10 producers: for (int i = 0; i < 10; ++i) { consumers[i] = std::thread(consumer); producers[i] = std::thread(producer,i + 1); } // join them back: for (int i = 0; i < 10; ++i) { producers[i].join(); consumers[i].join(); } return 0; }
std::condition_variable::notify_all() 介绍
唤醒全部的等待(wait)
线程。假设当前没有等待线程,则该函数什么也不做。请看以下的样例:
#include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex,i); std::cout << "10 threads ready to race...\n"; go(); // go! for (auto & th:threads) th.join(); return 0; }
std::condition_variable_any 介绍
与 std::condition_variable
相似。仅仅只是std::condition_variable_any
的 wait
函数能够接受不论什么 lockable
參数,而 std::condition_variable
仅仅能接受 std::unique_lock<std::mutex>
类型的參数,除此以外,和std::condition_variable
差点儿全然一样。
std::cv_status
枚举类型介绍
cv_status::no_timeout wait_for
或者wait_until
没有超时,即在规定的时间段内线程收到了通知。
cv_status::timeout wait_for 或者 wait_until 超时。 std::notify_all_at_thread_exit
函数原型为:
void notify_all_at_thread_exit (condition_variable& cond,unique_lock<mutex> lck);
当调用该函数的线程退出时,全部在 cond
条件变量上等待的线程都会收到通知。
请看下例(參考):
#include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex,std::unique_lock #include <condition_variable> // std::condition_variable std::mutex mtx; std::condition_variable cv; bool ready = false; void print_id (int id) { std::unique_lock<std::mutex> lck(mtx); while (!ready) cv.wait(lck); // ... std::cout << "thread " << id << ‘\n‘; } void go() { std::unique_lock<std::mutex> lck(mtx); std::notify_all_at_thread_exit(cv,std::move(lck)); ready = true; } int main () { std::thread threads[10]; // spawn 10 threads: for (int i=0; i<10; ++i) threads[i] = std::thread(print_id,i); std::cout << "10 threads ready to race...\n"; std::thread(go).detach(); // go! for (auto& th : threads) th.join(); return 0; }
<condition_variable>
头文件里的两个条件变量类(std::condition_variable
和std::condition_variable_any
)、枚举类型(std::cv_status
)、以及辅助函数(std::notify_all_at_thread_exit()
)都已经介绍完
从wait函数执行流程来看下条件变量的使用方法和原理:
https://blog.csdn.net/liu3612162/article/details/88343266
参考链接:
https://www.cnblogs.com/bhlsheji/p/5035018.html
https://www.cnblogs.com/wangshaowei/p/9593201.html
android ConditionVariable
1 /* 2 * copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.os; 18 19 /** 20 * Class that implements the condition variable locking paradigm. 21 * 22 * <p> 23 * This differs from the built-in java.lang.Object wait() and notify() 24 * in that this class contains the condition to wait on itself. That means 25 * open(), close() and block() are sticky. If open() is called before block(), 26 * block() will not block, and instead return immediately. 27 * 28 * <p> 29 * This class uses itself as the object to wait on, so if you wait() 30 * or notify() on a ConditionVariable, the results are undefined. 31 */ 32 public class ConditionVariable 33 { 34 private volatile boolean mCondition; 35 36 /** 37 * Create the ConditionVariable in the default closed state. 38 */ 39 public ConditionVariable() 40 { 41 mCondition = false; 42 } 43 44 /** 45 * Create the ConditionVariable with the given state. 46 * 47 * <p> 48 * Pass true for opened and false for closed. 49 */ 50 public ConditionVariable(boolean state) 51 { 52 mCondition = state; 53 } 54 55 /** 56 * Open the condition, and release all threads that are blocked. 57 * 58 * <p> 59 * Any threads that later approach block() will not block unless close() 60 * is called. 61 */ 62 public void open() 63 { 64 synchronized (this) { 65 boolean old = mCondition; 66 mCondition = true; 67 if (!old) { 68 this.notifyAll(); 69 } 70 } 71 } 72 73 /** 74 * Reset the condition to the closed state. 75 * 76 * <p> 77 * Any threads that call block() will block until someone calls open. 78 */ 79 public void close() 80 { 81 synchronized (this) { 82 mCondition = false; 83 } 84 } 85 86 /** 87 * Block the current thread until the condition is opened. 88 * 89 * <p> 90 * If the condition is already opened, return immediately. 91 */ 92 public void block() 93 { 94 synchronized (this) { 95 while (!mCondition) { 96 try { 97 this.wait(); 98 } 99 catch (InterruptedException e) { 100 } 101 } 102 } 103 } 104 105 /** 106 * Block the current thread until the condition is opened or until 107 * timeoutMs milliseconds have passed. 108 * 109 * <p> 110 * If the condition is already opened, return immediately. 111 * 112 * @param timeoutMs the maximum time to wait in milliseconds. 113 * 114 * @return true if the condition was opened, false if the call returns 115 * because of the timeout. 116 */ 117 public boolean block(long timeoutMs) 118 { 119 // Object.wait(0) means wait forever, to mimic this, we just 120 // call the other block() method in that case. It simplifies 121 // this code for the common case. 122 if (timeoutMs != 0) { 123 synchronized (this) { 124 long Now = SystemClock.elapsedRealtime(); 125 long end = Now + timeoutMs; 126 while (!mCondition && Now < end) { 127 try { 128 this.wait(end-Now); 129 } 130 catch (InterruptedException e) { 131 } 132 Now = SystemClock.elapsedRealtime(); 133 } 134 return mCondition; 135 } 136 } else { 137 this.block(); 138 return true; 139 } 140 } 141 }
android.os.ConditionVariable的实例源码
/** * Creates an audio track using the specified audio capabilities and stream type. * * @param audioCapabilities The current audio playback capabilities. * @param streamType The type of audio stream for the underlying {@link android.media.AudioTrack}. */ public AudioTrack(AudioCapabilities audioCapabilities,int streamType) { this.audioCapabilities = audioCapabilities; this.streamType = streamType; releasingConditionVariable = new ConditionVariable(true); if (Util.SDK_INT >= 18) { try { getLatencyMethod = android.media.AudioTrack.class.getmethod("getLatency",(Class<?>[]) null); } catch (NoSuchMethodException e) { // There's no guarantee this method exists. Do nothing. } } if (Util.SDK_INT >= 23) { audioTrackUtil = new AudioTrackUtilV23(); } else if (Util.SDK_INT >= 19) { audioTrackUtil = new AudioTrackUtilV19(); } else { audioTrackUtil = new AudioTrackUtil(); } playheadOffsets = new long[MAX_PLAYHEAD_OFFSET_COUNT]; volume = 1.0f; startMediaTimeState = START_NOT_SET; }
c – std :: condition_variable :: wait_until的实现
template<typename _Clock,typename _Duration> cv_status wait_until(unique_lock<mutex>& __lock,const chrono::time_point<_Clock,_Duration>& __atime) { // DR 887 - Sync unkNown clock to kNown clock. const typename _Clock::time_point __c_entry = _Clock::Now(); const __clock_t::time_point __s_entry = __clock_t::Now(); const auto __delta = __atime - __c_entry; const auto __s_atime = __s_entry + __delta; return __wait_until_impl(__lock,__s_atime); } template<typename _Clock,typename _Duration,typename _Predicate> bool wait_until(unique_lock<mutex>& __lock,_Duration>& __atime,_Predicate __p) { while (!__p()) if (wait_until(__lock,__atime) == cv_status::timeout) return __p(); return true; }
第二个函数调用循环中的第一个函数.它将执行时钟同步操作.如果我们调用第二个函数,同步操作可能会运行多次.每次都需要同步时钟吗?我认为代码可以改进在第二个功能中只通过同步时钟一次.对吧?
解决方法
是的,可以优化此代码,以便在循环时不操作time_points.但是,我不确定这是否真的有必要.
考虑是什么使得谓词wait_until
循环.
当notified时,它检查谓词以查看是否有工作要做.
>如果谓词返回true,即条件变量保护的条件为真,则wait_until返回true.
>如果超时过去,wait_until将返回谓词的值,该值通常为false(否则我们会预期condition_variable已被通知).
这只留下一个循环实际循环的情况:当通知condition_variable时,谓词返回false.
这被称为spurious wakeup,并不是典型的情况,所以它并不值得优化.
c – `std :: condition_variable :: wait_for`经常调用谓词
#include <iostream> #include <condition_variable> #include <chrono> #include <mutex> int main () { std::mutex y; std::condition_variable x; std::unique_lock<std::mutex>lock{y}; int i = 0; auto increment = [&] {++i; return false;}; using namespace std::chrono_literals; //lock 5s if increment returns false //let's see how often was increment called? x.wait_for(lock,5s,increment); std::cout << i << std::endl; //compare this with a simple loop: //how often can my system call increment in 5s? auto const end = std::chrono::system_clock::Now() + 5s; i = 0; while (std::chrono::system_clock::Now() < end) { increment(); } std::cout << i; }
据我所知wait_for,在wait_for之后我应该是O(1)(让我们假设虚假解锁很少见).
但是,我明白了
对于内核4.17.14,Intel(R)Core(TM)i7-6700 cpu @ 3.40GHz,i~ = 3e8,
对于内核3.10.0,Intel(R)Xeon(R)cpu E5-2630 v4 @ 2.20GHz,i~ = 8e6.
这听起来很有趣,所以我通过比较一个运行5秒的简单循环来检查. i的结果大致相同,只有5-10%的差异.
题:
wait_for在做什么?它是否按预期工作,我只是理解cppreference错误,或者我搞砸了?
第二,(可选)问题:我的这个巨大差异来自哪里?
附加信息:
(gcc7.3,gcc8.2,clang6.0),flags:-O3 –std = c 17都可以得到可比较的结果.
解决方法
请参阅此libstdc错误:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58929
您需要在编译命令中添加“-pthread”.
今天关于C++11并行编程-条件变量(condition_variable)详细说明和c++条件变量使用的介绍到此结束,谢谢您的阅读,有关android ConditionVariable、android.os.ConditionVariable的实例源码、c – std :: condition_variable :: wait_until的实现、c – `std :: condition_variable :: wait_for`经常调用谓词等更多相关知识的信息可以在本站进行查询。
本文标签: