在c ++ 11中使用带std :: thread的atomics [英] Using atomics with std::thread in c++11

查看:132
本文介绍了在c ++ 11中使用带std :: thread的atomics的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程,我想坐在一个循环,直到我准备好退出程序,在这一点,我想它打破循环,退出,所以我可以调用 std :: thread :: join 就可以了。在c ++ 03的日子里,我只是使用一个bool保护锁,以告诉线程何时退出。这一次我想我会利用新的原子库(特别是 std :: atomic_bool ),但我有麻烦。下面是我的测试用例:

I have a thread that I want to sit in a loop until I'm ready to exit the program, at which point I want it to break out of the loop and exit so I can call std::thread::join on it. In the days of c++03, I would just use a bool protected by a lock in order to tell the thread when to exit. This time I thought I would take advantage of the new atomics library (specifically std::atomic_bool), but I'm having trouble. Below is my test case:

#include <atomic>
#include <thread>
#include <cstdio>

using namespace std;

void setBool(atomic_bool& ab)
{
    ab = true;
}

int main()
{
    atomic_bool b;
    b = false;
    thread t(setBool, b);
    t.join();
    printf("Atomic bool value: %d\n", b.load());
    return 0;
}

线程t 当我尝试编译时,会出现怪物。错误的中心部分似乎是:

The declaration of thread t spits out this monstrosity when I try to compile. The central part of the error seems to be:


无法初始化类型为'std :: atomic_bool&'的非const引用为什么我不能得到 atomic_bool

invalid initialization of non-const reference of type ‘std::atomic_bool&’ from an rvalue of type ‘std::atomic_bool’



?我应该怎么办?

Why can I not get a reference to an atomic_bool? What should I do instead?

推荐答案

你必须明确传递一个ref到你的线程。使用 std :: ref 将创建一个 std :: reference_wrapper ,它是可复制的,

You have to explicitly pass a ref to your thread. Using std::ref will create a std::reference_wrapper which is copyable and will carry the ref to your function.

thread t(setBool, std::ref(b));

否则会尝试复制原子,这是不可复制的。

Otherwise it will try to copy your atomic, which is uncopyable.

这篇关于在c ++ 11中使用带std :: thread的atomics的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆