-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDMAController.cpp
More file actions
79 lines (61 loc) · 1.54 KB
/
DMAController.cpp
File metadata and controls
79 lines (61 loc) · 1.54 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "DMAController.h"
#include <fstream>
#include <iostream>
using namespace std;
DMAController::DMAController() {
isRunning = true;
workerThread = thread(&DMAController::workerLoop, this);
}
void DMAController::stopThreads() {
isRunning = false;
conditionVar.notify_all();
if (workerThread.joinable()) {
workerThread.join();
}
}
DMAController::~DMAController() {
stopThreads();
}
void DMAController::scheduleWrite(string path, vector<char> data) {
{
lock_guard<mutex> lock(queueMutex);
workQueue.push({ path, data });
}
conditionVar.notify_one();
}
void DMAController::workerLoop() {
while (isRunning) {
Request req;
{
// ensures only 1 worker uses queue at a time
// => prevents workers from popping garbage memory from queue
unique_lock<mutex> lock(queueMutex);
// tells the thread to yield until there's work in the queue
// or manually told to be put be on yield again
conditionVar.wait(lock, [this] {
return !workQueue.empty() || !isRunning;
});
if (!isRunning && workQueue.empty()) return;
// only one thread can run here at a time
req = workQueue.front();
workQueue.pop();
}
ofstream file(req.filepath, ios::binary | ios::app);
if (file.is_open()) {
file.write(req.data.data(), req.data.size());
}
else {
cerr << "Error in DMA: " << req.filepath << endl;
}
}
}
void DMAController::waitForCompletion() {
while (true) {
unique_lock<mutex> lock(queueMutex);
if (workQueue.empty()) {
break;
}
lock.unlock();
this_thread::sleep_for(chrono::milliseconds(10));
}
}