【C++编程】条件变量condition_variable
std::condition_variable 条件变量
void wait( std::unique_lock<std::mutex>& lock ); #1
template< class Predicate >
void wait( std::unique_lock<std::mutex>& lock, Predicate stop_waiting ); #2
多线程轮流打印ABC
#include <iostream>
#include <thread>
#include <condition_variable>
#include <vector>
#include <algorithm>
#include <functional>
#include <thread>
#include <mutex>
std::mutex mtx;
std::condition_variable variable;
char g_ch = 0;
void print_fun(char ch) {
int cyle_cnt = 10;
char ch_ = ch - 'A';
for (int i = 0; i < cyle_cnt; i++) {
std::unique_lock<std::mutex> ulk(mtx);
variable.wait(ulk, [ch_] { return ch_ == g_ch; });
std::cout << (char)(ch_ + 'A') << std::endl;
g_ch = (ch_ + 1) % 3;
ulk.unlock();
variable.notify_all();
}
}
int main()
{
std::vector<std::thread> threads;
threads.push_back(std::thread(print_fun, 'A'));
threads.push_back(std::thread(print_fun, 'B'));
threads.push_back(std::thread(print_fun, 'C'));
std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
std::cout << std::endl;
return 0;
}
例1 :
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
void worker_thread()
{
std::unique_lock lk(m);
cv.wait(lk, [] { return ready; });
std::cout << "Worker thread is processing data\n";
data += " after processing";
processed = true;
std::cout << "Worker thread signals data processing completed\n";
lk.unlock();
cv.notify_one();
}
int main()
{
std::thread worker(worker_thread);
data = "Example data";
{
std::lock_guard lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
{
std::unique_lock lk(m);
cv.wait(lk, [] { return processed; });
}
std::cout << "Back in main(), data = " << data << '\n';
worker.join();
}