C++ 11 thread condition menu variable

condition_variable

(C++11)

provides a condition variable associated with a std::unique_lock

condition_variable
  
(C ++ 11)
 
Provides the condition variable associated with STD:: unique'lock

Example

condition_variable is used in combination with a std::mutex to facilitate inter-thread communication.

Example 1
condition_variable is used in combination with STD:: mutex to facilitate inter thread communication.

When a wait function of the STD:: condition ﹣ variable object is called, it uses STD:: unique ﹣ lock (through std::mutex) to lock the current thread. The current thread will be blocked until another thread calls the notification function on the same STD:: condition \ variable object to wake up the current thread.

STD:: condition ﹣ variable object usually uses STD:: unique ﹣ lock < STD:: mutex > to wait. If you need to use another type of lock, you can use the STD:: condition ﹣ variable ﹣ any class. Later in this article, we will talk about the use of STD:: condition ﹣ variable ﹣ any.

// threadTest.cpp: defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>

std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;

void worker_thread()
{
	//std::this_thread::sleep_for(std::chrono::seconds(1));
	// wait until main() sends data
	std::unique_lock<std::mutex> lk(m);
	std::cout << "thread lk.lock\n";
	// here m will be unlocked,and will wait other thread notify ,if recive other thread notify,this thread will go on.
	cv.wait(lk, [] {return ready; });

	// after the wait, we own the lock
	std::cout << "Worker thread is processing data\n";
	data += " after processing";

	// send data back to main()
	processed = true;
	std::cout << "Worker thread signals data processing completed\n";

	// Manual unlocking is done befor nodifying, to avoid waking up
	// the waiting thread only to block again (see notify_one for details)
	lk.unlock();
	cv.notify_one();
}
int main()
{
	std::thread worker(worker_thread);
	data = "Example data";
	// send data to the worker thread
	{
		std::lock_guard<std::mutex> lk(m);
		std::cout << "main lk.lock\n";
		ready = true;
		std::cout << "main() signals data ready for processing\n";
	}
	cv.notify_one();

	// wait for the worker

	{
		std::unique_lock<std::mutex> lk(m);
		cv.wait(lk, [] {return processed; });
	}

	std::cout << "Back in main(),data = " << data << '\n';
	worker.join();
    return 0;
}

Operation result:

cv.wait() unlock s the lock and waits for it. If another thread sends a notification, it continues to execute and locks the lock.

Example 2

// threadTest.cpp: defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <queue>
class condvarQueue
{
	std::queue<int> produced_nums;
	std::mutex m;
	std::condition_variable cond_var;
	bool done = false;
	bool notified = false;
public:
	void push(int i)
	{
		std::unique_lock<std::mutex> lock(m);
		produced_nums.push(i);
		notified = true;
		cond_var.notify_one();
	}

	template<typename Consumer>
	void consume(Consumer consumer)
	{
		std::unique_lock<std::mutex> lock(m);
		while (!done) {
			while (!notified) {
				cond_var.wait(lock);
			}
			while (!produced_nums.empty()) {
				consumer(produced_nums.front());
				produced_nums.pop();
			}
			notified = false;
		}
	}

	void close()
	{
		done = true;
		notified = true;
		cond_var.notify_one();
	}

 };
int main()
{
	condvarQueue queue;

	std::thread producer([&]() {
		for (int i = 0; i < 5; i++) {
			std::this_thread::sleep_for(std::chrono::seconds(1));
			std::cout << "producing" << i << '\n';
			queue.push(i);
		}
		queue.close();
	});

	std::thread consumer([&]() {
		queue.consume([](int input) {
			std::cout << "consuming " << input << '\n';
		});
	});
	producer.join();
	consumer.join();
    return 0;
}

Operation result:

producing0
consuming 0
producing1
consuming 1
producing2
consuming 2
producing3
consuming 3
producing4
consuming 4
Please press any key to continue

Example 3. Notify all

// threadTest.cpp: defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <queue>

std::condition_variable cv;
std::mutex cv_m;// This mutex is used for three purposes
				// 1) to synchronize accesses to i
				// 2) to synchronize accesses to std::cerr
				// 3) for the condition variable cv
int i = 0;

void waits()
{
	std::unique_lock<std::mutex> lk(cv_m);
	std::cerr << "Waiting... \n";
	cv.wait(lk, [] {return i == 1; });// only when i ==1, wait will return
	std::cerr << "...finished waiting.i == 1\n";
}

void signals()
{
	std::this_thread::sleep_for(std::chrono::seconds(1));
	{
		std::lock_guard<std::mutex> lk(cv_m);
		std::cerr << "Notifying...\n";
	}
	cv.notify_all();
	
	std::this_thread::sleep_for(std::chrono::seconds(1));
	{
		std::lock_guard<std::mutex> lk(cv_m);
		i = 1;
		std::cerr << "Notifying again...\n";
	}
	cv.notify_all();
}
int main()
{
	std::thread t1(waits), t2(waits), t3(waits), t4(signals);
	t1.join();
	t2.join();
	t3.join();
	t4.join();
    return 0;
}



//output
/*
Waiting...
Waiting...
Waiting...
Notifying...
Notifying again...
...finished waiting.i == 1
...finished waiting.i == 1
...finished waiting.i == 1
 Please press any key to continue
*/

 

Published 253 original articles, won 20 praises and 90000 visitors+
Private letter follow

Posted on Fri, 13 Mar 2020 08:18:12 -0700 by Robert07