我有两个功能
void f(const int &x) {}
void g(int& x) {}
我可以做
int x = 0;
std::thread t1(f, x);
但是我无法创建 std::thread t2(g, x)
,在这种情况下我需要 make std::ref(x)
而不仅仅是x
,为什么有必要?
为什么可以在没有 std::cref
的情况下创建 t1
?
最佳答案
如果没有 std::cref()
,您的 f()
函数将无法按预期工作。
尽管 f()
无意更改 x
后面的值,但这并不意味着该引用后面的值不能在其他地方发生变化。
在此示例中,如果没有 std::cref()
,原始 int
的拷贝将放入线程堆栈中,并且 x
引用本拷贝;我们看到 1
和 1
。
另一方面,使用 std::cref()
时,x
仍然引用原始内容;我们看到 1
和 2
。
/**
g++ -std=c++17 -o prog_cpp prog_cpp.cpp \
-pedantic -Wall -Wextra -Wconversion -Wno-sign-conversion \
-g -O0 -UNDEBUG -fsanitize=address,undefined -pthread
**/
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
void
f(const int &x)
{
std::cout << "x=" << x << '\n';
std::this_thread::sleep_for(1000ms);
std::cout << "x=" << x << '\n';
}
int
main()
{
int i=1;
// std::thread th{f, i}; // copy to thread stack
std::thread th{f, std::cref(i)}; // reference the original i
std::this_thread::sleep_for(500ms);
i+=1;
th.join();
return 0;
}
关于c++ - 引用 std::thread 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66321253/