# HG changeset patch # User Alain Mazy # Date 1778507409 -7200 # Node ID a5c8b1dcfaf55a2de079cd862716bd13df7b3aeb # Parent a7dbb19622fda9d35b9c9a9e6774baa35906dfac# Parent c5173fb5f2d274c49d72908325c612224ef33c2e merge diff -r a7dbb19622fd -r a5c8b1dcfaf5 OrthancFramework/Sources/MultiThreading/FutureState.cpp --- a/OrthancFramework/Sources/MultiThreading/FutureState.cpp Mon May 11 15:49:34 2026 +0200 +++ b/OrthancFramework/Sources/MultiThreading/FutureState.cpp Mon May 11 15:50:09 2026 +0200 @@ -66,15 +66,23 @@ case State_Failed: if (error_.get() == NULL) { - throw OrthancException(ErrorCode_InternalError); // Should never happen + throw OrthancException(ErrorCode_BadSequenceOfCalls, "The result of the future has already been released"); } else { - throw OrthancException(*error_); + std::unique_ptr released(error_.release()); + throw OrthancException(*released); } case State_Success: - return result_.release(); + if (result_.get() == NULL) + { + throw OrthancException(ErrorCode_BadSequenceOfCalls, "The result of the future has already been released"); + } + else + { + return result_.release(); + } default: throw OrthancException(ErrorCode_InternalError); // Should never happen @@ -143,7 +151,7 @@ assert(error_.get() == NULL); error_.reset(new OrthancException(error)); - state_ = State_Success; + state_ = State_Failed; completed_.notify_all(); break; diff -r a7dbb19622fd -r a5c8b1dcfaf5 OrthancFramework/Sources/MultiThreading/ThreadPool.cpp --- a/OrthancFramework/Sources/MultiThreading/ThreadPool.cpp Mon May 11 15:49:34 2026 +0200 +++ b/OrthancFramework/Sources/MultiThreading/ThreadPool.cpp Mon May 11 15:50:09 2026 +0200 @@ -25,10 +25,11 @@ #include "../PrecompiledHeaders.h" #include "ThreadPool.h" +#include "../Logging.h" #include "../OrthancException.h" #include "FutureState.h" -static const unsigned int DEQUEUE_TIMEOUT_MS = 100; +static const unsigned int DEFAULT_DEQUEUE_TIMEOUT_MS = 100; namespace Orthanc @@ -72,24 +73,120 @@ // Nothing to do: The future was canceled before we even started } } + + void Cancel() + { + boost::shared_ptr locked = state_.lock(); + + if (locked) + { + locked->SetError(OrthancException(ErrorCode_CanceledJob)); + } + else + { + // Nothing to do: The future was canceled before we even started + } + } }; + void ThreadPool::StopInternal(bool throws) + { + { + boost::mutex::scoped_lock lock(mutex_); + + switch (state_) + { + case State_Initialization: + if (throws) + { + throw OrthancException(ErrorCode_BadSequenceOfCalls, "Start() has not been called"); + } + else + { + return; // This is for the destructor + } + + case State_Finalization: + if (throws) + { + throw OrthancException(ErrorCode_BadSequenceOfCalls, "Concurrent access to Stop()"); + } + else + { + return; // This is for the destructor, should never happen + } + + case State_Running: + state_ = State_Finalization; + break; + + default: + if (throws) + { + throw OrthancException(ErrorCode_InternalError); + } + else + { + return; // This is for the destructor + } + } + } + + workers_.join_all(); + + // Cancel all the remaining tasks in the queue + for (;;) + { + std::unique_ptr task(queue_.Dequeue(1)); + + if (task.get() == NULL) + { + break; + } + else + { + try + { + dynamic_cast(*task).Cancel(); + } + catch (OrthancException& e) + { + LOG(ERROR) << "Error while canceling task during shutdown: " << e.What(); + } + } + } + + { + boost::mutex::scoped_lock lock(mutex_); + state_ = State_Initialization; + } + } + + void ThreadPool::WorkerLoop() { while (true) { - std::unique_ptr task(queue_.Dequeue(DEQUEUE_TIMEOUT_MS)); + unsigned int timeout; - if (task.get() == NULL) { - boost::mutex::scoped_lock lock(shutdownMutex_); - if (shutdown_) + boost::mutex::scoped_lock lock(mutex_); + + if (state_ == State_Running) { + timeout = dequeueTimeoutMilliseconds_; + } + else + { + assert(state_ == State_Finalization); return; } } - else + + std::unique_ptr task(queue_.Dequeue(timeout)); + + if (task.get() != NULL) { dynamic_cast(*task).Execute(); } @@ -97,34 +194,105 @@ } - ThreadPool::ThreadPool(unsigned int countThreads) : - shutdown_(false) + ThreadPool::ThreadPool() : + countThreads_(1), + state_(State_Initialization), + dequeueTimeoutMilliseconds_(DEFAULT_DEQUEUE_TIMEOUT_MS) { - if (countThreads < 1) + } + + + void ThreadPool::SetCountThreads(unsigned int count) + { + if (count < 1) { throw OrthancException(ErrorCode_ParameterOutOfRange); } - for (unsigned int i = 0; i < countThreads; i++) { - workers_.create_thread(boost::bind(&ThreadPool::WorkerLoop, this)); + boost::mutex::scoped_lock lock(mutex_); + + if (state_ == State_Initialization) + { + countThreads_ = count; + } + else + { + throw OrthancException(ErrorCode_BadSequenceOfCalls, "Start() has already been called"); + } } } - ThreadPool::~ThreadPool() + unsigned int ThreadPool::GetCountThreads() { + boost::mutex::scoped_lock lock(mutex_); + return countThreads_; + } + + + void ThreadPool::SetDequeueTimeout(unsigned int milliseconds) + { + if (milliseconds < 1) { - boost::mutex::scoped_lock lock(shutdownMutex_); - shutdown_ = true; + throw OrthancException(ErrorCode_ParameterOutOfRange); } - workers_.join_all(); + { + boost::mutex::scoped_lock lock(mutex_); + + if (state_ == State_Initialization) + { + dequeueTimeoutMilliseconds_ = milliseconds; + } + else + { + throw OrthancException(ErrorCode_BadSequenceOfCalls, "Start() has already been called"); + } + } + } + + + unsigned int ThreadPool::GetDequeueTimeout() + { + boost::mutex::scoped_lock lock(mutex_); + return dequeueTimeoutMilliseconds_; + } + + + void ThreadPool::Start() + { + boost::mutex::scoped_lock lock(mutex_); + + if (state_ == State_Initialization) + { + assert(countThreads_ >= 1); + + state_ = State_Running; + + for (unsigned int i = 0; i < countThreads_; i++) + { + workers_.create_thread(boost::bind(&ThreadPool::WorkerLoop, this)); + } + } + else + { + throw OrthancException(ErrorCode_BadSequenceOfCalls, "Start() has not been called"); + } } Future* ThreadPool::Submit(ICallable* callable) { + { + boost::mutex::scoped_lock lock(mutex_); + + if (state_ != State_Running) + { + throw OrthancException(ErrorCode_BadSequenceOfCalls, "The thread pool is not running"); + } + } + std::unique_ptr protection(callable); if (callable == NULL) diff -r a7dbb19622fd -r a5c8b1dcfaf5 OrthancFramework/Sources/MultiThreading/ThreadPool.h --- a/OrthancFramework/Sources/MultiThreading/ThreadPool.h Mon May 11 15:49:34 2026 +0200 +++ b/OrthancFramework/Sources/MultiThreading/ThreadPool.h Mon May 11 15:50:09 2026 +0200 @@ -35,19 +35,48 @@ class ORTHANC_PUBLIC ThreadPool : public IExecutorService { private: + enum State + { + State_Initialization, + State_Running, + State_Finalization + }; + class Task; SharedMessageQueue queue_; boost::thread_group workers_; - boost::mutex shutdownMutex_; - bool shutdown_; + boost::mutex mutex_; + unsigned int countThreads_; + State state_; + unsigned int dequeueTimeoutMilliseconds_; + + void StopInternal(bool throws); void WorkerLoop(); public: - ThreadPool(unsigned int countThreads); + ThreadPool(); + + ~ThreadPool() + { + StopInternal(false /* don't throw in destructor */); + } + + void SetCountThreads(unsigned int count); + + unsigned int GetCountThreads(); - ~ThreadPool(); + void SetDequeueTimeout(unsigned int milliseconds); + + unsigned int GetDequeueTimeout(); + + void Start(); + + void Stop() + { + StopInternal(true); + } virtual Future* Submit(ICallable* callable /* takes ownership */) ORTHANC_OVERRIDE; }; diff -r a7dbb19622fd -r a5c8b1dcfaf5 OrthancFramework/UnitTestsSources/JobsTests.cpp --- a/OrthancFramework/UnitTestsSources/JobsTests.cpp Mon May 11 15:49:34 2026 +0200 +++ b/OrthancFramework/UnitTestsSources/JobsTests.cpp Mon May 11 15:50:09 2026 +0200 @@ -45,6 +45,7 @@ #include "../../OrthancFramework/Sources/Logging.h" #include "../../OrthancFramework/Sources/MultiThreading/BlockingSharedMessageQueue.h" #include "../../OrthancFramework/Sources/MultiThreading/SharedMessageQueue.h" +#include "../../OrthancFramework/Sources/MultiThreading/ThreadPool.h" #include "../../OrthancFramework/Sources/OrthancException.h" #include "../../OrthancFramework/Sources/SerializationToolbox.h" @@ -1811,3 +1812,94 @@ ASSERT_TRUE(SerializationToolbox::ParseDouble(i, "1.3671875")); ASSERT_DOUBLE_EQ(1.3671875, i); } } + + +namespace +{ + static boost::mutex counterMutex_; + static unsigned int counter_ = 10; + + class CountCallable : public ICallable + { + public: + virtual IDynamicObject* Call() ORTHANC_OVERRIDE + { + boost::mutex::scoped_lock lock(counterMutex_); + return new SingleValueObject(counter_++); + } + }; + + class ExceptionCallable : public ICallable + { + public: + virtual IDynamicObject* Call() ORTHANC_OVERRIDE + { + throw OrthancException(ErrorCode_NetworkProtocol); // dummy error code + } + }; +} + + +TEST(ThreadPool, Basic) +{ + ThreadPool pool; + ASSERT_THROW(pool.SetCountThreads(0), OrthancException); + ASSERT_THROW(pool.SetDequeueTimeout(0), OrthancException); + pool.SetDequeueTimeout(1); // Ensure fast shutdown in unit tests + ASSERT_EQ(1u, pool.GetCountThreads()); + ASSERT_EQ(1u, pool.GetDequeueTimeout()); + + pool.Start(); + ASSERT_THROW(pool.Start(), OrthancException); + + pool.Stop(); + ASSERT_THROW(pool.Stop(), OrthancException); + + ASSERT_EQ(10u, counter_); + + pool.Start(); + + { + std::unique_ptr future1(pool.Submit(new CountCallable)); + std::unique_ptr future2(pool.Submit(new ExceptionCallable)); + + { + std::unique_ptr result(future1->ReleaseResult()); + ASSERT_EQ(10u, dynamic_cast< SingleValueObject&>(*result).GetValue()); + } + + try + { + std::unique_ptr result(future2->ReleaseResult()); + ASSERT_TRUE(false); + } + catch (OrthancException& e) + { + ASSERT_EQ(ErrorCode_NetworkProtocol, e.GetErrorCode()); + } + + try + { + std::unique_ptr result(future1->ReleaseResult()); + ASSERT_TRUE(false); + } + catch (OrthancException& e) + { + ASSERT_EQ(ErrorCode_BadSequenceOfCalls, e.GetErrorCode()); + } + + try + { + std::unique_ptr result(future2->ReleaseResult()); + ASSERT_TRUE(false); + } + catch (OrthancException& e) + { + ASSERT_EQ(ErrorCode_BadSequenceOfCalls, e.GetErrorCode()); + } + } + + pool.Stop(); + + ASSERT_EQ(11u, counter_); +}