1  
//
1  
//
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3  
// Copyright (c) 2026 Michael Vandeberg
3  
// Copyright (c) 2026 Michael Vandeberg
4  
//
4  
//
5  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
5  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
6  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7  
//
7  
//
8  
// Official repository: https://github.com/boostorg/capy
8  
// Official repository: https://github.com/boostorg/capy
9  
//
9  
//
10  

10  

11  
#include <boost/capy/ex/thread_pool.hpp>
11  
#include <boost/capy/ex/thread_pool.hpp>
12  
#include <boost/capy/detail/intrusive.hpp>
12  
#include <boost/capy/detail/intrusive.hpp>
13  
#include <boost/capy/test/thread_name.hpp>
13  
#include <boost/capy/test/thread_name.hpp>
 
14 +
#include <atomic>
14  
#include <condition_variable>
15  
#include <condition_variable>
15  
#include <cstdio>
16  
#include <cstdio>
16  
#include <mutex>
17  
#include <mutex>
17  
#include <thread>
18  
#include <thread>
18  
#include <vector>
19  
#include <vector>
19  

20  

20  
/*
21  
/*
21  
    Thread pool implementation using a shared work queue.
22  
    Thread pool implementation using a shared work queue.
22  

23  

23  
    Work items are coroutine handles wrapped in intrusive list nodes, stored
24  
    Work items are coroutine handles wrapped in intrusive list nodes, stored
24  
    in a single queue protected by a mutex. Worker threads wait on a
25  
    in a single queue protected by a mutex. Worker threads wait on a
25  
    condition_variable until work is available or stop is requested.
26  
    condition_variable until work is available or stop is requested.
26  

27  

27  
    Threads are started lazily on first post() via std::call_once to avoid
28  
    Threads are started lazily on first post() via std::call_once to avoid
28  
    spawning threads for pools that are constructed but never used. Each
29  
    spawning threads for pools that are constructed but never used. Each
29  
    thread is named with a configurable prefix plus index for debugger
30  
    thread is named with a configurable prefix plus index for debugger
30  
    visibility.
31  
    visibility.
31  

32  

32  
    Shutdown sequence: stop() sets the stop flag and notifies all threads,
33  
    Shutdown sequence: stop() sets the stop flag and notifies all threads,
33  
    then the destructor joins threads and destroys any remaining queued
34  
    then the destructor joins threads and destroys any remaining queued
34  
    work without executing it.
35  
    work without executing it.
35  
*/
36  
*/
36  

37  

37  
namespace boost {
38  
namespace boost {
38  
namespace capy {
39  
namespace capy {
39  

40  

40  
//------------------------------------------------------------------------------
41  
//------------------------------------------------------------------------------
41  

42  

42  
class thread_pool::impl
43  
class thread_pool::impl
43  
{
44  
{
44  
    struct work : detail::intrusive_queue<work>::node
45  
    struct work : detail::intrusive_queue<work>::node
45  
    {
46  
    {
46  
        std::coroutine_handle<> h_;
47  
        std::coroutine_handle<> h_;
47  

48  

48  
        explicit work(std::coroutine_handle<> h) noexcept
49  
        explicit work(std::coroutine_handle<> h) noexcept
49  
            : h_(h)
50  
            : h_(h)
50  
        {
51  
        {
51  
        }
52  
        }
52  

53  

53  
        void run()
54  
        void run()
54  
        {
55  
        {
55  
            auto h = h_;
56  
            auto h = h_;
56  
            delete this;
57  
            delete this;
57  
            h.resume();
58  
            h.resume();
58  
        }
59  
        }
59  

60  

60  
        void destroy()
61  
        void destroy()
61  
        {
62  
        {
62  
            delete this;
63  
            delete this;
63  
        }
64  
        }
64  
    };
65  
    };
65  

66  

66  
    std::mutex mutex_;
67  
    std::mutex mutex_;
67  
    std::condition_variable cv_;
68  
    std::condition_variable cv_;
68  
    detail::intrusive_queue<work> q_;
69  
    detail::intrusive_queue<work> q_;
69  
    std::vector<std::thread> threads_;
70  
    std::vector<std::thread> threads_;
70 -
    bool stop_{false};
71 +
    std::atomic<bool> stop_{false};
71  
    std::size_t num_threads_;
72  
    std::size_t num_threads_;
72  
    char thread_name_prefix_[13]{};  // 12 chars max + null terminator
73  
    char thread_name_prefix_[13]{};  // 12 chars max + null terminator
73  
    std::once_flag start_flag_;
74  
    std::once_flag start_flag_;
74  

75  

75  
public:
76  
public:
76  
    ~impl()
77  
    ~impl()
77  
    {
78  
    {
78  
        stop();
79  
        stop();
79  
        for(auto& t : threads_)
80  
        for(auto& t : threads_)
80  
            if(t.joinable())
81  
            if(t.joinable())
81  
                t.join();
82  
                t.join();
82  

83  

83  
        while(auto* w = q_.pop())
84  
        while(auto* w = q_.pop())
84  
            w->destroy();
85  
            w->destroy();
85  
    }
86  
    }
86  

87  

87  
    impl(std::size_t num_threads, std::string_view thread_name_prefix)
88  
    impl(std::size_t num_threads, std::string_view thread_name_prefix)
88  
        : num_threads_(num_threads)
89  
        : num_threads_(num_threads)
89  
    {
90  
    {
90  
        if(num_threads_ == 0)
91  
        if(num_threads_ == 0)
91  
            num_threads_ = std::thread::hardware_concurrency();
92  
            num_threads_ = std::thread::hardware_concurrency();
92  
        if(num_threads_ == 0)
93  
        if(num_threads_ == 0)
93  
            num_threads_ = 1;
94  
            num_threads_ = 1;
94  

95  

95  
        // Truncate prefix to 12 chars, leaving room for up to 3-digit index.
96  
        // Truncate prefix to 12 chars, leaving room for up to 3-digit index.
96  
        auto n = thread_name_prefix.copy(thread_name_prefix_, 12);
97  
        auto n = thread_name_prefix.copy(thread_name_prefix_, 12);
97  
        thread_name_prefix_[n] = '\0';
98  
        thread_name_prefix_[n] = '\0';
98  
    }
99  
    }
99  

100  

100  
    void
101  
    void
101  
    post(std::coroutine_handle<> h)
102  
    post(std::coroutine_handle<> h)
102  
    {
103  
    {
103  
        ensure_started();
104  
        ensure_started();
104  
        auto* w = new work(h);
105  
        auto* w = new work(h);
105  
        {
106  
        {
106  
            std::lock_guard<std::mutex> lock(mutex_);
107  
            std::lock_guard<std::mutex> lock(mutex_);
107  
            q_.push(w);
108  
            q_.push(w);
108  
        }
109  
        }
109  
        cv_.notify_one();
110  
        cv_.notify_one();
110  
    }
111  
    }
111  

112  

112 -
    join() noexcept
 
113 -
    {
 
114 -
        stop();
 
115 -
        for(auto& t : threads_)
 
116 -
            if(t.joinable())
 
117 -
                t.join();
 
118 -
    }
 
119 -

 
120 -
    void
 
121  
    void
113  
    void
122  
    stop() noexcept
114  
    stop() noexcept
123  
    {
115  
    {
124 -
        {
116 +
        stop_.store(true, std::memory_order_release);
125 -
            std::lock_guard<std::mutex> lock(mutex_);
 
126 -
            stop_ = true;
 
127 -
        }
 
128  
        cv_.notify_all();
117  
        cv_.notify_all();
129  
    }
118  
    }
130  

119  

131  
private:
120  
private:
132  
    void
121  
    void
133  
    ensure_started()
122  
    ensure_started()
134  
    {
123  
    {
135  
        std::call_once(start_flag_, [this]{
124  
        std::call_once(start_flag_, [this]{
136  
            threads_.reserve(num_threads_);
125  
            threads_.reserve(num_threads_);
137  
            for(std::size_t i = 0; i < num_threads_; ++i)
126  
            for(std::size_t i = 0; i < num_threads_; ++i)
138  
                threads_.emplace_back([this, i]{ run(i); });
127  
                threads_.emplace_back([this, i]{ run(i); });
139  
        });
128  
        });
140  
    }
129  
    }
141  

130  

142  
    void
131  
    void
143  
    run(std::size_t index)
132  
    run(std::size_t index)
144  
    {
133  
    {
145  
        // Build name; set_current_thread_name truncates to platform limits.
134  
        // Build name; set_current_thread_name truncates to platform limits.
146  
        char name[16];
135  
        char name[16];
147  
        std::snprintf(name, sizeof(name), "%s%zu", thread_name_prefix_, index);
136  
        std::snprintf(name, sizeof(name), "%s%zu", thread_name_prefix_, index);
148  
        set_current_thread_name(name);
137  
        set_current_thread_name(name);
149  

138  

150  
        for(;;)
139  
        for(;;)
151  
        {
140  
        {
152  
            work* w = nullptr;
141  
            work* w = nullptr;
153  
            {
142  
            {
154  
                std::unique_lock<std::mutex> lock(mutex_);
143  
                std::unique_lock<std::mutex> lock(mutex_);
155  
                cv_.wait(lock, [this]{
144  
                cv_.wait(lock, [this]{
156  
                    return !q_.empty() ||
145  
                    return !q_.empty() ||
157 -
                        stop_;
146 +
                        stop_.load(std::memory_order_acquire);
158  
                });
147  
                });
159 -
                if(stop_ && q_.empty())
148 +
                if(stop_.load(std::memory_order_acquire) && q_.empty())
160  
                    return;
149  
                    return;
161  
                w = q_.pop();
150  
                w = q_.pop();
162  
            }
151  
            }
163  
            if(w)
152  
            if(w)
164  
                w->run();
153  
                w->run();
165  
        }
154  
        }
166  
    }
155  
    }
167  
};
156  
};
168  

157  

169  
//------------------------------------------------------------------------------
158  
//------------------------------------------------------------------------------
170  

159  

171  
thread_pool::
160  
thread_pool::
172  
~thread_pool()
161  
~thread_pool()
173 -
    impl_->join();
 
174  
{
162  
{
175  
    shutdown();
163  
    shutdown();
176  
    destroy();
164  
    destroy();
177  
    delete impl_;
165  
    delete impl_;
178  
}
166  
}
179  

167  

180  
thread_pool::
168  
thread_pool::
181  
thread_pool(std::size_t num_threads, std::string_view thread_name_prefix)
169  
thread_pool(std::size_t num_threads, std::string_view thread_name_prefix)
182  
    : impl_(new impl(num_threads, thread_name_prefix))
170  
    : impl_(new impl(num_threads, thread_name_prefix))
183  
{
171  
{
184  
    this->set_frame_allocator(std::allocator<void>{});
172  
    this->set_frame_allocator(std::allocator<void>{});
185  
}
173  
}
186  

174  

187  
void
175  
void
188  
thread_pool::
176  
thread_pool::
189  
stop() noexcept
177  
stop() noexcept
190  
{
178  
{
191  
    impl_->stop();
179  
    impl_->stop();
192  
}
180  
}
193  

181  

194 -

 
195 -
thread_pool::executor_type
 
196 -
thread_pool::
 
197 -
get_executor() const noexcept
 
198 -
{
 
199 -
    return executor_type(
 
200 -
        const_cast<thread_pool&>(*this));
 
201 -
}
 
202  
//------------------------------------------------------------------------------
182  
//------------------------------------------------------------------------------
203  

183  

204  
void
184  
void
205  
thread_pool::executor_type::
185  
thread_pool::executor_type::
206  
post(std::coroutine_handle<> h) const
186  
post(std::coroutine_handle<> h) const
207  
{
187  
{
208  
    pool_->impl_->post(h);
188  
    pool_->impl_->post(h);
209  
}
189  
}
210  

190  

211  
} // capy
191  
} // capy
212  
} // boost
192  
} // boost