-
Notifications
You must be signed in to change notification settings - Fork 1
/
Producer.h
82 lines (71 loc) · 2.04 KB
/
Producer.h
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* @file Producer.h
*
* @brief Producer class for pushing elements into shared thread-safe container.
*
* @author Hovsep Papoyan
* Contact: papoyanhovsep93@gmail.com
* @Date 2024-01-10
*
*/
#ifndef PRODUCER_H
#define PRODUCER_H
#include "ProducerConsumerBase.h"
namespace mt
{
template<typename Adapter>
class Producer : public ProducerConsumerBase<Adapter>
{
private:
using Super = ProducerConsumerBase<Adapter>;
using Elem = typename Adapter::Elem;
decltype(createThreadSafeSTLAdapterFrom(std::queue<std::vector<Elem>>{})) m_vectorItemsQueue;
public:
explicit Producer(Adapter& sharedContainer);
Producer(const Producer&) = default;
Producer(Producer&&) = default;
Producer& operator=(const Producer&) = default;
Producer& operator=(Producer&) = default;
~Producer() override;
void push(std::vector<Elem> items);
private:
void workerThreadWork() override;
};
template<typename Adapter>
Producer<Adapter>::Producer(Adapter& sharedContainer)
: Super(Super::Type::Producer, sharedContainer)
, m_vectorItemsQueue(createThreadSafeSTLAdapterFrom(std::queue<std::vector<Elem>>{}))
{
this->runMainThread();
}
template<typename Adapter>
Producer<Adapter>::~Producer()
{
this->shutdownMainThread();
}
template<typename Adapter>
void Producer<Adapter>::push(std::vector<Elem> items)
{
m_vectorItemsQueue.push(std::move(items));
}
template<typename Adapter>
void Producer<Adapter>::workerThreadWork()
{
while (this->m_workerThreadEnabled)
{
std::vector<Elem> vectorItem;
if (m_vectorItemsQueue.tryPop(vectorItem))
{
for (auto& item : vectorItem)
{
this->m_sharedContainer.push(std::move(item));
}
}
else
{
std::this_thread::yield();
}
}
}
} // namespace mt
#endif