Skip to content

Commit

Permalink
Guard service_.run() in threadpool::add().
Browse files Browse the repository at this point in the history
  • Loading branch information
evoskuil committed Dec 16, 2024
1 parent 2b0175e commit ac1b5b5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
12 changes: 8 additions & 4 deletions include/bitcoin/network/async/threadpool.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,16 @@ class BCT_API threadpool final
// Join the specified thread.
bool join(std::thread& thread) NOEXCEPT;

// These are thread safe.
thread_priority priority_;
// This is thread safe.
const thread_priority priority_;

// This is protected by mutex.
// io_context is thread safe but we are isolating service_.poll().
std::mutex service_mutex_{};
asio::io_context service_{};
std::mutex mutex_{};

// These are (partially) protected by mutex.
// These are protected by mutex.
std::mutex threads_mutex_{};
std::vector<std::thread> threads_{};
bool stopped_;

Expand Down
14 changes: 6 additions & 8 deletions src/async/threadpool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
#include <bitcoin/network/async/threadpool.hpp>

#include <algorithm>
#include <mutex>
#include <thread>
#include <bitcoin/system.hpp>
Expand Down Expand Up @@ -56,28 +57,25 @@ threadpool::~threadpool() NOEXCEPT

size_t threadpool::add() NOEXCEPT
{
std::unique_lock lock(mutex_);

std::unique_lock lock(threads_mutex_);
const auto size = threads_.size();
if (stopped_ || size == limit)
return size;

threads_.push_back(std::thread([this]() NOEXCEPT
threads_.push_back(std::thread([this]()
{
set_priority(priority_);

// If service.run throws, application will abort at startup.
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
std::unique_lock guard(service_mutex_);
service_.run();
BC_POP_WARNING()
}));

return add1(size);
}

size_t threadpool::remove() NOEXCEPT
{
std::unique_lock lock(mutex_);
std::unique_lock lock(threads_mutex_);

const auto size = threads_.size();
if (is_zero(size))
Expand Down Expand Up @@ -134,7 +132,7 @@ bool threadpool::join(std::thread& thread) NOEXCEPT
bool threadpool::join() NOEXCEPT
{
// This exists due to add/remove.
std::unique_lock lock(mutex_);
std::unique_lock lock(threads_mutex_);

for (auto& thread: threads_)
if (!join(thread))
Expand Down

0 comments on commit ac1b5b5

Please sign in to comment.