C ++ 11 hilos condition_variable

condition_variable

(C ++ 11)

proporciona una variable de estado asociado con un  std :: unique_lock

condition_variable
  
(C ++ 11)
 
provisto de unique_lock variable de std :: condición asociada 

Ejemplo

condition_variable se utiliza en combinación con un  std :: mutex  para facilitar la comunicación inter-hilo.

 Ejemplo. 1
condition_variable y std :: mutex utilizado para facilitar la comunicación entre los hilos de unión.

Cuando una función de espera std :: condition_variable objeto se llama, utiliza std :: unique_lock para bloquear el hilo actual (a través de std :: mutex). El hilo actual siempre será bloqueado hasta que otro hilo llama a una función de notificación en la misma std :: condition_variable objeto de despertar el subproceso actual.

std :: condition_variable utilizar regularmente std :: unique_lock <std :: mutex> espera, si es necesario utilizando el tipo de cerradura adicional, puede ser usado std :: clases condition_variable_any se mencionarán más adelante en el presente documento, std :: uso condition_variable_any.

// threadTest.cpp : 定义控制台应用程序的入口点。
//
#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;
}

El resultado:

 cv.wait () bloqueará de desbloqueo, y luego esperar a su cuenta, si otro hilo envía una notificación, continuará y se bloqueará de bloqueo.

Ejemplo 2

// threadTest.cpp : 定义控制台应用程序的入口点。
//
#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;
}

El resultado:

producing0
El consumo de 0
producing1
consumo. 1
producing2
El consumo de 2
producing3
consumo. 3
producing4
consumo. 4
Pulse cualquier tecla para continuar.

例 3 .notify_all

// threadTest.cpp : 定义控制台应用程序的入口点。
//
#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
请按任意键继续. . .
*/

 

Publicados 257 artículos originales · ganado elogios 22 · Vistas a 90000 +

Supongo que te gusta

Origin blog.csdn.net/qq_24127015/article/details/104834610
Recomendado
Clasificación