首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >错误:静态断言失败: std::thread参数[...]但是参数的数量是正确的

错误:静态断言失败: std::thread参数[...]但是参数的数量是正确的
EN

Stack Overflow用户
提问于 2021-04-13 21:47:58
回答 1查看 224关注 0票数 0

下面是我的代码:

代码语言:javascript
运行
复制
#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();
}

但我得到以下错误:

代码语言:javascript
运行
复制
/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,但我确信我的参数数量是正确的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-13 21:51:56

在创建线程时,它的参数会被复制,这会导致线程函数将引用作为参数时出现问题。

您需要使用std::ref包装要作为引用传递的对象(对于常量引用,则使用std::cref ):

代码语言:javascript
运行
复制
threads.emplace_back(work, std::ref(a));
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67076160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档