File tree Expand file tree Collapse file tree 5 files changed +30
-12
lines changed
Expand file tree Collapse file tree 5 files changed +30
-12
lines changed Original file line number Diff line number Diff line change 1+ {
2+ "files.associations" : {
3+ "mutex" : " cpp"
4+ }
5+ }
Original file line number Diff line number Diff line change 11#include " scheduler.hpp"
22#include < iostream>
3+ #include < chrono>
4+ #include < thread>
35
46int 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}
Original file line number Diff line number Diff 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- }
Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments