Untitled

 avatar
unknown
plain_text
2 years ago
807 B
7
Indexable
#include <thread>
#include <iostream>
#include <chrono>
#include <mutex>
#include <deque>
using namespace std;
mutex mu;
deque<int> q;


void producer() {
	int count = 10;
	while (count > 0)
	{
		unique_lock<mutex> locker(mu);
		/*
			CRITICAL REGION
		*/
		q.push_front(count);
		locker.unlock();

		this_thread::sleep_for(chrono::seconds(1));
		count--;
	}
}

void consumer() {
	int data = 0;
	while (data != 1)
	{
		unique_lock<mutex> locker(mu);

		/*
			CRITICAL REGION
		*/

		if (!q.empty()) {
			data = q.back();
			q.pop_back();
			locker.unlock();

			cout << "t2 got a value from t1: " << data << endl;
		}
		else {
			locker.unlock();
		}
	}
}

int main() {
	thread t1(producer);
	thread t2(consumer);

	t1.join();
	t2.join();
	return 0;
}
Editor is loading...