thread() noexcept;
|
(1) | (C++11 起) |
thread( thread&& other ) noexcept;
|
(2) | (C++11 起) |
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args ); |
(3) | (C++11 起) |
thread(const thread&) = delete;
|
(4) | (C++11 起) |
构造新的 thread 对象。
other
所表示的执行线程的 thread 对象。此调用后 other
不再表示执行线程。std::thread
对象并将它与执行线程关联。新的执行线程开始执行 std::invoke(decay_copy(std::forward<Function>(f)), decay_copy(std::forward<Args>(args))...);
其中 decay_copy
定义为
template <class T> std::decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); }
decay_copy
的调用在调用方语境求值,故而任何求值和复制/移动参数中抛出的异常被抛到当前线程,而不用开始新线程。
若 std::decay_t<Function> 是与 std::thread 相同的类型,则此构造函数不参与重载决议。
|
(C++14 起) |
std::thread
对象可表示同一执行线程。目录 |
other | - | 用以构造此 thread 的另一 thread 对象 |
f | - | 执行于新线程的可调用对象 (Callable )
|
args... | - | 传递给新函数的参数 |
std::errc::resource_unavailable_try_again
或另一实现限定的错误条件。到线程函数的参数被移动或按值复制。若需要传递引用参数给线程函数,则必须包装它(例如用 std::ref 或 std::cref )。
忽略来自函数的任何返回值。若函数抛异常,则调用 std::terminate 。为将返回值或异常传递回调用方线程,可使用 std::promise 或 std::async 。
#include <iostream> #include <utility> #include <thread> #include <chrono> #include <functional> #include <atomic> void f1(int n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 1 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void f2(int& n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 2 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } int main() { int n = 0; std::thread t1; // t1 非线程 std::thread t2(f1, n + 1); // 按值传递 std::thread t3(f2, std::ref(n)); // 按引用传递 std::thread t4(std::move(t3)); // t4 现在运行 f2() 。 t3 不再是线程 t2.join(); t4.join(); std::cout << "Final value of n is " << n << '\n'; }
可能的输出:
Thread 1 executing Thread 2 executing Thread 1 executing Thread 2 executing Thread 1 executing Thread 2 executing Thread 1 executing Thread 2 executing Thread 2 executing Thread 1 executing Final value of n is 5
thrd_create的 C 文档
|