由于此代碼段無法編譯,因此我std::thread了解callable&&除了callable&.
#include <iostream>
#include <cmath>
#include <thread>
#include <future>
#include <functional>
// unique function to avoid disambiguating the std::pow overload set
int f(int x, int y) { return std::pow(x,y); }
void task_thread()
{
std::packaged_task<int(int,int)> task(f);
std::future<int> result = task.get_future();
std::thread task_td(task, 2, 10); //std::move(task) works
task_td.join();
std::cout << "task_thread:\t" << result.get() << '\n';
}
int main()
{
task_thread();
}
根據std::thread需要callable&&,為什么下面的這段代碼有效?在這個代碼片段中,f1是一個普通函式,我認為它是一個callable&非callable&&.
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
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));
}
}
class foo
{
public:
void bar()
{
for (int i = 0; i < 5; i) {
std::cout << "Thread 3 executing\n";
n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int n = 0;
};
class baz
{
public:
void operator()()
{
for (int i = 0; i < 5; i) {
std::cout << "Thread 4 executing\n";
n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int n = 0;
};
int main()
{
int n = 0;
foo f;
baz b;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n 1); // pass by value
std::thread t3(f2, std::ref(n)); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
std::thread t5(&foo::bar, &f); // t5 runs foo::bar() on object f
std::thread t6(b); // t6 runs baz::operator() on a copy of object b
t2.join();
t4.join();
t5.join();
t6.join();
std::cout << "Final value of n is " << n << '\n';
std::cout << "Final value of f.n (foo::n) is " << f.n << '\n';
std::cout << "Final value of b.n (baz::n) is " << b.n << '\n';
}
uj5u.com熱心網友回復:
std::thread通過“衰減復制”獲取它給出的所有物件(要呼叫的函式及其引數)。這實際上意味著將為給定的每個引數創建一個新物件。std::thread在新執行緒上呼叫您的函式時,這些物件將被存盤并使用。如果您提供左值,新物件將通過復制創建,如果您提供 xvalue 或純右值,則通過移動創建。
這意味著,默認情況下,std::thread 不會參考建構式呼叫本身之外的變數。這也意味著它需要顯式的努力(std::ref或類似的努力)才能通過不屬于被呼叫執行緒的引數來訪問物件。
packaged_task是只移動型別。編譯失敗是因為你沒有呼叫std::move它,所以衰減復制試圖復制型別。由于它是只能移動的,因此編譯失敗。但這是 的屬性packaged_task,而不是 的屬性std::thread。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/440822.html
上一篇:全域多載前綴運算子 /--
