Din*_*gus 1 c++ multithreading
我刚刚开始学习多线程编程,我正在尝试更改主函数中声明的变量。我的主要功能如下:
#include <iostream>
#include <thread>
void foo(int &args)
{
for (int i = 0; i < 10; i++)
{
args = rand() % 100;
}
}
int main()
{
int args;
std::thread worker(foo, args);
for (int i = 0; i < 10; i++)
{
std::cout << args << std::endl;
}
worker.join();
}
Run Code Online (Sandbox Code Playgroud)
所以我希望 main 函数做的是将 args 作为引用并更改位于该内存地址上的值。然而 Thread 不喜欢这个想法。我通过运行这一小段代码收到的实际消息是:
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/10.2.0/../../../../include/c++/10.2.0/thread:135:2: error: static_assert failed due to requirement '__is_invocable<void (*)(int &), int>::value' "std::thread arguments must be invocable after conversion to rvalues"
static_assert( __is_invocable<typename decay<_Callable>::type,
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
multThread.cpp:15:17: note: in instantiation of function template specialization 'std::thread::thread<void (&)(int &), int &, void>' requested here
std::thread worker(foo, args);
Run Code Online (Sandbox Code Playgroud)
还有更多,但我发现用错误消息完全填充这篇文章是多余的。我不太确定是什么导致了这个问题,是线程只接受右值还是什么?预先感谢您的帮助。
要将引用参数传递给std::thread,您需要reference_wrapper在调用站点将其转换为 a ,如下所示:
std::thread worker(foo, std::ref(args));
Run Code Online (Sandbox Code Playgroud)
这是因为std::thread复制其参数,而无法复制引用。
| 归档时间: |
|
| 查看次数: |
8164 次 |
| 最近记录: |