下面是我的代码:
#include <atomic>
#include <thread>
#include <vector>
int num_of_threads = 4;
// Simple function for incrementing an atomic int
void work(std::atomic<int>& a) {
for (int i = 0; i < 100000; i++) {
a++;
}
}
void test() {
std::atomic<int> a;
a = 0;
std::vector<std::thread> threads;
threads.reserve(num_of_threads);
for (size_t i = 0; i < num_of_threads; i++) {
threads.emplace_back(work, a); //<- here is the issue
}
for (auto& thread : threads) {
thread.join();
}
}
int main() {
test();
}
但我得到以下错误:
/usr/include/c++/10.2.0/thread:136:44: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
136 | typename decay<_Args>::type...>::value,
我也查了这个问题,here,但我确信我的参数数量是正确的。
发布于 2021-04-13 21:51:56
在创建线程时,它的参数会被复制,这会导致线程函数将引用作为参数时出现问题。
您需要使用std::ref
包装要作为引用传递的对象(对于常量引用,则使用std::cref
):
threads.emplace_back(work, std::ref(a));
https://stackoverflow.com/questions/67076160
复制相似问题