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 <condition_variable>
14  
#include <condition_variable>
15  
#include <cstdio>
15  
#include <cstdio>
16  
#include <mutex>
16  
#include <mutex>
17  
#include <thread>
17  
#include <thread>
18  
#include <vector>
18  
#include <vector>
19  

19  

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

22  

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

26  

27  
    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
28  
    spawning threads for pools that are constructed but never used. Each
28  
    spawning threads for pools that are constructed but never used. Each
29  
    thread is named with a configurable prefix plus index for debugger
29  
    thread is named with a configurable prefix plus index for debugger
30  
    visibility.
30  
    visibility.
31  

31  

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

36  

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

39  

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

41  

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

47  

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

52  

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

59  

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

65  

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

74  

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

82  

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

86  

87  
    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)
88  
        : num_threads_(num_threads)
88  
        : num_threads_(num_threads)
89  
    {
89  
    {
90  
        if(num_threads_ == 0)
90  
        if(num_threads_ == 0)
91  
            num_threads_ = std::thread::hardware_concurrency();
91  
            num_threads_ = std::thread::hardware_concurrency();
92  
        if(num_threads_ == 0)
92  
        if(num_threads_ == 0)
93  
            num_threads_ = 1;
93  
            num_threads_ = 1;
94  

94  

95  
        // 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.
96  
        auto n = thread_name_prefix.copy(thread_name_prefix_, 12);
96  
        auto n = thread_name_prefix.copy(thread_name_prefix_, 12);
97  
        thread_name_prefix_[n] = '\0';
97  
        thread_name_prefix_[n] = '\0';
98  
    }
98  
    }
99  

99  

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

111  

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

120  

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

130  

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

141  

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

149  

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

168  

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

170  

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

179  

180  
thread_pool::
180  
thread_pool::
181  
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)
182  
    : impl_(new impl(num_threads, thread_name_prefix))
182  
    : impl_(new impl(num_threads, thread_name_prefix))
183  
{
183  
{
184  
    this->set_frame_allocator(std::allocator<void>{});
184  
    this->set_frame_allocator(std::allocator<void>{});
185  
}
185  
}
186  

186  

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

193  

194  
//------------------------------------------------------------------------------
194  
//------------------------------------------------------------------------------
195  

195  

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

203  

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

210  

211  
} // capy
211  
} // capy
212  
} // boost
212  
} // boost