Skip to content
Snippets Groups Projects
synchronous_producer.hpp 701 B
Newer Older
#include <mutex>
#include <thread>
#include <chrono>
#include <deque>
using namespace std::literals::chrono_literals;

#include "items.hpp"

template <size_t sleep_duration_ms>
struct Producer_Sync {
	Item consume()
	{
		while (!done){
			std::this_thread::sleep_for(10ms);
		}
		if (channel.empty()){
			return Item{-1};
		}
		auto ret = channel.front();
		channel.pop_front();
		return ret;

	};

	void produce(size_t n_times)
	{
		done = false;
		for (size_t i = 0; i < n_times; i++){
			std::this_thread::sleep_for(std::chrono::milliseconds{sleep_duration_ms});
			channel.push_back(Item{(int)i});
		}
		done = true;

	}
private:
	bool done = false;
	std::mutex m{};
	std::deque<Item> channel;
};