-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultithread_packet_processor.cpp
More file actions
62 lines (48 loc) · 1.65 KB
/
multithread_packet_processor.cpp
File metadata and controls
62 lines (48 loc) · 1.65 KB
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
#include "multithreaded_packet_processor.h"
#include <iostream>
MultithreadedPacketProcessor::MultithreadedPacketProcessor(
size_t threadCount,
const std::function<void(const std::string&)>& processPacket)
: threadCount(threadCount), processPacket(processPacket), stopFlag(false) {}
// Start the worker threads
void MultithreadedPacketProcessor::start() {
for (size_t i = 0; i < threadCount; ++i) {
threads.emplace_back(&MultithreadedPacketProcessor::workerThread, this);
}
}
// Enqueue a packet for processing bc wdym ive to wait in line
void MultithreadedPacketProcessor::enqueuePacket(const std::string& packetData) {
{
std::lock_guard<std::mutex> lock(queueMutex);
packetQueue.push(packetData);
}
condition.notify_one(); // packet arrival notification sent to one thread (will come back to this later)
}
void MultithreadedPacketProcessor::stop() {
{
std::lock_guard<std::mutex> lock(queueMutex);
stopFlag = true;
}
condition.notify_all(); // Notify all threads to exit
for (auto& thread : threads) {
if (thread.joinable()) {
thread.join();
}
}
}
// Worker thread function
void MultithreadedPacketProcessor::workerThread() {
while (true) {
std::string packetData;
{
std::unique_lock<std::mutex> lock(queueMutex);
condition.wait(lock, [this]() { return !packetQueue.empty() || stopFlag; });
if (stopFlag && packetQueue.empty()) {
return;
}
packetData = packetQueue.front();
packetQueue.pop();
}
processPacket(packetData);
}
}