Seastar
High performance C++ framework for concurrent servers
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Modules Pages
thread.hh
1/*
2 * This file is open source software, licensed to you under the terms
3 * of the Apache License, Version 2.0 (the "License"). See the NOTICE file
4 * distributed with this work for additional information regarding copyright
5 * ownership. You may not use this file except in compliance with the License.
6 *
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing,
12 * software distributed under the License is distributed on an
13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 * KIND, either express or implied. See the License for the
15 * specific language governing permissions and limitations
16 * under the License.
17 */
18
19/*
20 * Copyright (C) 2015 Cloudius Systems, Ltd.
21 */
22
23#pragma once
24
25#ifndef SEASTAR_MODULE
26#include <seastar/core/thread_impl.hh>
27#include <seastar/core/future.hh>
28#include <seastar/core/do_with.hh>
29#include <seastar/core/timer.hh>
31#include <memory>
32#include <type_traits>
33#include <seastar/util/assert.hh>
34#include <seastar/util/std-compat.hh>
35#include <seastar/util/modules.hh>
36#include <ucontext.h>
37#include <boost/intrusive/list.hpp>
38#endif
39
69
71namespace seastar {
72
75SEASTAR_MODULE_EXPORT_BEGIN
76class thread;
77class thread_attributes;
78
81public:
82 std::optional<seastar::scheduling_group> sched_group;
83 // For stack_size 0, a default value will be used (128KiB when writing this comment)
84 size_t stack_size = 0;
85};
86SEASTAR_MODULE_EXPORT_END
87
89extern thread_local jmp_buf_link g_unthreaded_context;
90
91// Internal class holding thread state. We can't hold this in
92// \c thread itself because \c thread is movable, and we want pointers
93// to this state to be captured.
94class thread_context final : private task {
95 struct stack_deleter {
96 void operator()(char *ptr) const noexcept;
97 int valgrind_id;
98 stack_deleter(int valgrind_id);
99 };
100 using stack_holder = std::unique_ptr<char[], stack_deleter>;
101
102 stack_holder _stack;
103 noncopyable_function<void ()> _func;
104 jmp_buf_link _context;
105 promise<> _done;
106 bool _joined = false;
107
108 boost::intrusive::list_member_hook<> _all_link;
109 using all_thread_list = boost::intrusive::list<thread_context,
110 boost::intrusive::member_hook<thread_context, boost::intrusive::list_member_hook<>,
111 &thread_context::_all_link>,
112 boost::intrusive::constant_time_size<false>>;
113
114 static thread_local all_thread_list _all_threads;
115private:
116 static void s_main(int lo, int hi); // all parameters MUST be 'int' for makecontext
117 void setup(size_t stack_size);
118 void main();
119 stack_holder make_stack(size_t stack_size);
120 virtual void run_and_dispose() noexcept override; // from task class
121public:
122 thread_context(thread_attributes attr, noncopyable_function<void ()> func);
123 ~thread_context();
124 void switch_in();
125 void switch_out();
126 bool should_yield() const;
127 void reschedule();
128 void yield();
129 task* waiting_task() noexcept override { return _done.waiting_task(); }
130 friend class thread;
131 friend void thread_impl::switch_in(thread_context*);
132 friend void thread_impl::switch_out(thread_context*);
133 friend scheduling_group thread_impl::sched_group(const thread_context*);
134};
135
137
138SEASTAR_MODULE_EXPORT
145class thread {
146 std::unique_ptr<thread_context> _context;
147 static thread_local thread* _current;
148public:
151 thread() = default;
156 template <typename Func>
157 thread(Func func);
163 template <typename Func>
164 thread(thread_attributes attr, Func func);
166 thread(thread&& x) noexcept = default;
168 thread& operator=(thread&& x) noexcept = default;
172 ~thread() { SEASTAR_ASSERT(!_context || _context->_joined); }
177 future<> join();
182 static void yield();
187 static bool should_yield() {
188 return need_preempt();
189 }
190
195 static void maybe_yield() {
196 if (should_yield()) [[unlikely]] {
197 yield();
198 }
199 }
200
201 static bool running_in_thread() {
202 return thread_impl::get() != nullptr;
203 }
204};
205
206template <typename Func>
207inline
209 : _context(std::make_unique<thread_context>(std::move(attr), std::move(func))) {
210}
211
212template <typename Func>
213inline
215 : thread(thread_attributes(), std::move(func)) {
216}
217
218inline
221 _context->_joined = true;
222 return _context->_done.get_future();
223}
224
225SEASTAR_MODULE_EXPORT_BEGIN
249template <typename Func, typename... Args>
250inline
251futurize_t<std::invoke_result_t<Func, Args...>>
252async(thread_attributes attr, Func&& func, Args&&... args) noexcept {
253 using return_type = std::invoke_result_t<Func, Args...>;
254 struct work {
256 Func func;
257 std::tuple<Args...> args;
259 thread th{};
260 };
261
262 try {
263 auto wp = std::make_unique<work>(work{std::move(attr), std::forward<Func>(func), std::forward_as_tuple(std::forward<Args>(args)...)});
264 auto& w = *wp;
265 auto ret = w.pr.get_future();
266 w.th = thread(std::move(w.attr), [&w] {
267 futurize<return_type>::apply(std::move(w.func), std::move(w.args)).forward_to(std::move(w.pr));
268 });
269 return w.th.join().then([ret = std::move(ret)] () mutable {
270 return std::move(ret);
271 }).finally([wp = std::move(wp)] {});
272 } catch (...) {
273 return futurize<return_type>::make_exception_future(std::current_exception());
274 }
275}
276
286template <typename Func, typename... Args>
287inline
288futurize_t<std::invoke_result_t<Func, Args...>>
289async(Func&& func, Args&&... args) noexcept {
290 return async(thread_attributes{}, std::forward<Func>(func), std::forward<Args>(args)...);
291}
293
294SEASTAR_MODULE_EXPORT_END
295}
A representation of a possibly not-yet-computed value.
Definition: future.hh:1197
Definition: task.hh:34
thread - stateful thread of execution
Definition: thread.hh:145
~thread()
Destroys a thread object.
Definition: thread.hh:172
thread(thread &&x) noexcept=default
Moves a thread object.
static void maybe_yield()
Yield if this thread ought to call yield() now.
Definition: thread.hh:195
static void yield()
Voluntarily defer execution of current thread.
thread()=default
Constructs a thread object that does not represent a thread of execution.
static bool should_yield()
Checks whether this thread ought to call yield() now.
Definition: thread.hh:187
thread & operator=(thread &&x) noexcept=default
Move-assigns a thread object.
future yield() noexcept
Returns a future which is not ready but is scheduled to resolve soon.
Class that holds attributes controling the behavior of a thread.
Definition: thread.hh:80
futurize_t< std::invoke_result_t< Func, Args... > > async(thread_attributes attr, Func &&func, Args &&... args) noexcept
Definition: thread.hh:252
future join()
Waits for thread execution to terminate.
Definition: thread.hh:220
Seastar API namespace.
Definition: abort_on_ebadf.hh:26
STL namespace.
Converts a type to a future type, if it isn't already.
Definition: future.hh:1786