From 78351a9b76499d8c12056ee96e0fc6cf66fdb501 Mon Sep 17 00:00:00 2001 From: Antonin Portelli Date: Sun, 28 Nov 2021 23:51:56 +0000 Subject: [PATCH] better interface for critical threaded sections --- examples/exThreadPool.cpp | 8 ++++---- lib/Core/ThreadPool.cpp | 8 ++++++++ lib/Core/ThreadPool.hpp | 2 ++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/examples/exThreadPool.cpp b/examples/exThreadPool.cpp index 85c714d..f22ea43 100644 --- a/examples/exThreadPool.cpp +++ b/examples/exThreadPool.cpp @@ -12,15 +12,15 @@ int main(void) { pool.addJob([i, &pool](void) { + pool.critical([i](void) { - unique_lock lock(pool.getMutex()); cout << "job " << i << " wait for " << i*100 << " ms" << endl; - } + }); this_thread::sleep_for(chrono::milliseconds(i*100)); + pool.critical([i](void) { - unique_lock lock(pool.getMutex()); cout << "job " << i << " done" << endl; - } + }); }); } pool.terminate(); diff --git a/lib/Core/ThreadPool.cpp b/lib/Core/ThreadPool.cpp index de4f575..fa8e27e 100644 --- a/lib/Core/ThreadPool.cpp +++ b/lib/Core/ThreadPool.cpp @@ -92,6 +92,14 @@ void ThreadPool::addJob(Job newJob) condition_.notify_one(); } +// critical section //////////////////////////////////////////////////////////// +void ThreadPool::critical(Job fn) +{ + unique_lock lock(mutex_); + + fn(); +} + // wait for completion ///////////////////////////////////////////////////////// void ThreadPool::terminate(void) { diff --git a/lib/Core/ThreadPool.hpp b/lib/Core/ThreadPool.hpp index 5a504e5..6594a8e 100644 --- a/lib/Core/ThreadPool.hpp +++ b/lib/Core/ThreadPool.hpp @@ -37,6 +37,8 @@ public: std::mutex & getMutex(void); // add jobs void addJob(Job newJob); + // critical section + void critical(Job fn); // wait for completion and terminate void terminate(void); private: