error: static assertion failed: std::thread arguments [...] but the number of arguments is correct
error: static assertion failed: std::thread arguments [...] but the number of arguments is correct
这是我的代码:
#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,
我也查了这个问题,但我确定我的参数数量是正确的。
当创建一个线程时,它的参数被复制,这导致线程函数将引用作为参数的问题。
您需要包装要作为引用传递的对象,使用 std::ref
(或 std::cref
用于对常量的引用):
threads.emplace_back(work, std::ref(a));
这是我的代码:
#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,
我也查了这个问题
当创建一个线程时,它的参数被复制,这导致线程函数将引用作为参数的问题。
您需要包装要作为引用传递的对象,使用 std::ref
(或 std::cref
用于对常量的引用):
threads.emplace_back(work, std::ref(a));