Skip to content

Commit 16e3dbd

Browse files
committed
Implement task submission and add basic test
1 parent 69dd8fb commit 16e3dbd

File tree

5 files changed

+30
-12
lines changed

5 files changed

+30
-12
lines changed

.vscode/settings.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"files.associations": {
3+
"mutex": "cpp"
4+
}
5+
}

main.exe

36.4 KB
Binary file not shown.

src/main.cpp

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,25 @@
11
#include "scheduler.hpp"
22
#include <iostream>
3+
#include <chrono>
4+
#include <thread>
35

46
int main() {
57

6-
std::cout << "Hello, world!\n";
8+
// Create a scheduler with 4 worker threads
9+
Scheduler scheduler(4);
710

11+
// Submit some tasks
12+
for (int i = 0; i < 10; ++i) {
13+
scheduler.submit([i]() {
14+
std::cout << "Task " << i << " executed by thread\n";
15+
// Simulate some work
16+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
17+
});
18+
}
19+
20+
// Give tasks time to execute
21+
std::this_thread::sleep_for(std::chrono::seconds(2));
22+
23+
std::cout << "Main thread finished\n";
824
return 0;
925
}

src/scheduler.cpp

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,3 @@ Scheduler::Scheduler(size_t num_threads) : shutdown_(false) {
2929
});
3030
}
3131
}
32-
33-
template<typename F>
34-
void Scheduler::submit(F&& task) {
35-
{
36-
std::lock_guard<std::mutex> lock(queue_mutex_);
37-
task_queue_.emplace(std::forward<F>(task));
38-
}
39-
// Notify one waiting worker thread that a task is available
40-
condition_.notify_one();
41-
}

src/scheduler.hpp

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,14 @@ class Scheduler {
3131

3232
// Submit a task to be executed by a worker thread
3333
template<typename F>
34-
void submit(F&& task);
34+
void submit(F&& task) {
35+
{
36+
std::lock_guard<std::mutex> lock(queue_mutex_);
37+
task_queue_.emplace(std::forward<F>(task));
38+
}
39+
// Notify one waiting worker thread that a task is available
40+
condition_.notify_one();
41+
}
3542
};
3643

3744
#endif

0 commit comments

Comments
 (0)