std::jthread::jthread
|
|
jthread() noexcept;
|
(1) | (C++20 起) |
jthread(
jthread&& other )
noexcept;
|
(2) | (C++20 起) |
template< class Function, class... Args >
explicit jthread( Function&& f, Args&&... args ); |
(3) | (C++20 起) |
jthread( const jthread& ) = delete;
|
(4) | (C++20 起) |
构造新的 std::jthread
对象。
std::jthread
对象。std::jthread
对象表示之前由 other 表示的执行线程。此调用后
other
不再表示执行线程。std::jthread
对象。新的执行线程开始执行:
std::invoke(decay-copy(std::forward<Function>(f)), get_stop_token(), |
(C++23 前) |
std::invoke(auto(std::forward<Function>(f)), get_stop_token(), |
(C++23 起) |
如果以上表达式非良构,那么就会开始执行:
std::invoke(decay-copy(std::forward<Function>(f)), |
(C++23 前) |
std::invoke(auto(std::forward<Function>(f)), |
(C++23 起) |
std::jthread
是同一类型,那么此构造函数不会参与重载决议。std::jthread
对象不能表示同一执行线程。参数
other | - | 用来构造此 std::jthread 对象的另一 std::jthread 对象
|
f | - | 在新线程执行的可调用 (Callable) 对象 |
args... | - | 传递给函数的参数 |
后条件
异常
std::errc::resource_unavailable_try_again
或另一实现限定的错误条件。注解
移动或按值复制线程函数的参数。如果需要传递引用参数给线程函数,那么必须包装它(例如用 std::ref 或 std::cref)。
忽略来自函数的任何返回值。如果函数抛出异常,那么就会调用 std::terminate。需要将返回值或异常传递回调用方线程时可以使用 std::promise 或 std::async。
示例
#include <chrono> #include <iostream> #include <thread> #include <utility> using namespace std::literals; void f1(int n) { for (int i = 0; i < 5; ++i) { std::cout << "正在执行线程1\n"; ++n; std::this_thread::sleep_for(10ms); } } void f2(int& n) { for (int i = 0; i < 5; ++i) { std::cout << "正在执行线程2\n"; ++n; std::this_thread::sleep_for(10ms); } } class foo { public: void bar() { for (int i = 0; i < 5; ++i) { std::cout << "正在执行线程3\n"; ++n; std::this_thread::sleep_for(10ms); } } int n = 0; }; class baz { public: void operator()() { for (int i = 0; i < 5; ++i) { std::cout << "正在执行线程4\n"; ++n; std::this_thread::sleep_for(10ms); } } int n = 0; }; int main() { int n = 0; foo f; baz b; std::jthread t0; // t0 不是线程 std::jthread t1(f1, n + 1); // 按值传递 std::jthread t2a(f2, std::ref(n)); // 按引用传递 std::jthread t2b(std::move(t2a)); // t2b 现在运行 f2()。t2a 不再是线程 std::jthread t3(&foo::bar, &f); // t3 在对象 f 上运行 foo::bar() std::jthread t4(b); // t4 在对象 b 的副本上运行 baz::operator() t1.join(); t2b.join(); t3.join(); std::cout << "n 的最终值是 " << n << '\n'; std::cout << "f.n (foo::n) 的最终值是 " << f.n << '\n'; std::cout << "b.n (baz::n) 的最终值是 " << b.n << '\n'; // t4 在析构时结合 }
可能的输出:
正在执行线程2 正在执行线程1 正在执行线程4 正在执行线程3 正在执行线程3 正在执行线程4 正在执行线程2 正在执行线程1 正在执行线程3 正在执行线程1 正在执行线程4 正在执行线程2 正在执行线程3 正在执行线程1 正在执行线程4 正在执行线程2 正在执行线程3 正在执行线程1 正在执行线程4 正在执行线程2 n 的最终值是 5 f.n (foo::n) 的最终值是 5 b.n (baz::n) 的最终值是 0
参阅
构造新的 thread 对象 ( std::thread
的公开成员函数) |