Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#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_Streaming {
Item consume(){
Item ret;
while(!done && channel.empty()){
std::this_thread::sleep_for(10ms);
}
if (done && channel.empty()){
return Item{-1};
}
m.lock();
ret = channel.front();
channel.pop_front();
m.unlock();
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});
m.lock();
channel.push_back(Item{(int)i});
m.unlock();
}
done = true;
}
void reset(){
done = false;
}
private:
bool done = false;
std::mutex m;
std::deque<Item> channel;
};