关于传递给 std::thread 的构造函数的参数

About the parameters passed to the ctor of `std::thread`

由于此代码片段无法编译,我了解到 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';
}

std::thread通过“衰减复制”获取所有给它的对象(要调用的函数及其参数)。这实际上意味着将为给定的每个参数创建一个新对象。这些对象将由 std::thread 存储并在新线程上调用您的函数时使用。如果您提供左值,将通过复制创建新对象,如果您提供 xvalues 或 prvalues,则将通过移动创建新对象。

这意味着,默认情况下,std::thread 不会 引用构造函数调用本身之外的变量。这也意味着它需要明确的努力(std::ref 或类似的)通过不属于被调用线程的参数访问对象。

packaged_task 是 move-only 类型。编译失败,因为您没有对其调用 std::move,因此 decay-copy 试图复制该类型。因为是move-only,所以编译失败。但这是 packaged_task 的 属性,而不是 std::thread