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 <atomic>
 
14  
#include <boost/capy/test/thread_name.hpp>
13  
#include <boost/capy/test/thread_name.hpp>
15  
#include <condition_variable>
14  
#include <condition_variable>
16  
#include <cstdio>
15  
#include <cstdio>
17  
#include <mutex>
16  
#include <mutex>
18  
#include <thread>
17  
#include <thread>
19  
#include <vector>
18  
#include <vector>
20  

19  

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

22  

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

26  

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

31  

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

36  

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

39  

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

41  

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

47  

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

52  

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

59  

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

65  

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

74  

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

82  

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

86  

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

94  

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

99  

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

111  

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

120  

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

130  

129  
private:
131  
private:
130  
    void
132  
    void
131  
    ensure_started()
133  
    ensure_started()
132  
    {
134  
    {
133  
        std::call_once(start_flag_, [this]{
135  
        std::call_once(start_flag_, [this]{
134  
            threads_.reserve(num_threads_);
136  
            threads_.reserve(num_threads_);
135  
            for(std::size_t i = 0; i < num_threads_; ++i)
137  
            for(std::size_t i = 0; i < num_threads_; ++i)
136  
                threads_.emplace_back([this, i]{ run(i); });
138  
                threads_.emplace_back([this, i]{ run(i); });
137  
        });
139  
        });
138  
    }
140  
    }
139  

141  

140  
    void
142  
    void
141  
    run(std::size_t index)
143  
    run(std::size_t index)
142  
    {
144  
    {
143  
        // Build name; set_current_thread_name truncates to platform limits.
145  
        // Build name; set_current_thread_name truncates to platform limits.
144  
        char name[16];
146  
        char name[16];
145  
        std::snprintf(name, sizeof(name), "%s%zu", thread_name_prefix_, index);
147  
        std::snprintf(name, sizeof(name), "%s%zu", thread_name_prefix_, index);
146  
        set_current_thread_name(name);
148  
        set_current_thread_name(name);
147  

149  

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

168  

167  
//------------------------------------------------------------------------------
169  
//------------------------------------------------------------------------------
168  

170  

169  
thread_pool::
171  
thread_pool::
170  
~thread_pool()
172  
~thread_pool()
171  
{
173  
{
172  
    impl_->join();
174  
    impl_->join();
173  
    shutdown();
175  
    shutdown();
174  
    destroy();
176  
    destroy();
175  
    delete impl_;
177  
    delete impl_;
176  
}
178  
}
177  

179  

178  
thread_pool::
180  
thread_pool::
179  
thread_pool(std::size_t num_threads, std::string_view thread_name_prefix)
181  
thread_pool(std::size_t num_threads, std::string_view thread_name_prefix)
180  
    : impl_(new impl(num_threads, thread_name_prefix))
182  
    : impl_(new impl(num_threads, thread_name_prefix))
181  
{
183  
{
182  
    this->set_frame_allocator(std::allocator<void>{});
184  
    this->set_frame_allocator(std::allocator<void>{});
183  
}
185  
}
184  

186  

185  
void
187  
void
186  
thread_pool::
188  
thread_pool::
187  
stop() noexcept
189  
stop() noexcept
188  
{
190  
{
189  
    impl_->stop();
191  
    impl_->stop();
190  
}
192  
}
191  

193  

192  
//------------------------------------------------------------------------------
194  
//------------------------------------------------------------------------------
193  

195  

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

203  

202  
void
204  
void
203  
thread_pool::executor_type::
205  
thread_pool::executor_type::
204  
post(std::coroutine_handle<> h) const
206  
post(std::coroutine_handle<> h) const
205  
{
207  
{
206  
    pool_->impl_->post(h);
208  
    pool_->impl_->post(h);
207  
}
209  
}
208  

210  

209  
} // capy
211  
} // capy
210  
} // boost
212  
} // boost