c++ 线程函数按值接受对象:为什么 std::ref(obj) 可以编译?

问题描述 投票:0回答:1
#include <iostream>
#include <thread>

template<int Num>
class MyClass {
public:
    MyClass(int val) : val_(val) {}

private:
    int val_;
};

template<int Num>
void threadFunction(MyClass<Num> myObj) {
    std::cout << "Inside thread" << std::endl;
}

int main() {
    MyClass<1> obj(42);

    std::thread t1(threadFunction<1>, obj); // <-- pass by value
    std::thread t2(threadFunction<1>, std::ref(obj)); // <-- pass by reference

    t1.join();
    t2.join();

    return 0;
}

我想按值将对象传递给线程,以确保每个线程在自己的副本上工作(线程 t1)。

当我创建线程 t2 时,我使用 std::ref(obj) 通过引用传递对象。

显然,我对每个函数定义的意图是按值而不是按引用传递对象。如果在所有线程中作为 std::ref(obj) 传递,obj 是否是共享变量?

这个问题 std::ref 与模板函数和按值传递的函数一起使用 似乎解决了类似的主题,但不是在多线程上下文中。在此处显示的示例中,如果函数是模板化的,则似乎存在差异。

c++ multithreading function
1个回答
0
投票

为什么无法编译?

如果在所有线程中作为 std::ref(obj) 传递,obj 是否是共享变量?

不。每个线程都会获得一个副本。

情况类似

 void foo( int a) { std::cout << a; }

 int main() {
     int x = 42;
     int& ref = x;
     foo(ref);
 }

ref
是对
x
的引用。当您调用
foo(ref)
时,
a
x
的副本。

© www.soinside.com 2019 - 2024. All rights reserved.