C ++ std :: atomic与Boost原子 [英] C++ std::atomic vs. Boost atomic

查看:895
本文介绍了C ++ std :: atomic与Boost原子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个int和一个bool变量,被多个线程访问(多个写/读)。目前,我使用两个互斥体,一个为int,一个为bool保护这些变量。

In my application, I have an int and a bool variable, which are accessed (multiple write/read) by multiple threads. Currently, I am using two mutexes, one for int and one for bool to protect those variables.

我听说过使用原子变量和操作符来写锁,线程程序。我的问题是

I heard about using atomic variables and operators to write lock-free multi-thread program. My questions are


  1. 原子变量和运算符的定义是什么?

  2. std :: atomic
    boost / atomic.hpp ?哪一个更标准或更流行?

  3. 这些库是平台相关的吗?我现在使用gnu gcc 4.6 on
    Linux,但理想情况下它应该是跨平台的。我听说原子的定义实际上还取决于硬件。任何人都可以解释一下吗?

  4. 在多个线程之间共享bool变量的最好方法是什么?我不想使用 volatile 关键字。

  1. What's the definition of atomic variables and operators?
  2. What's the main difference between std::atomic and boost/atomic.hpp? Which one is more standard or popular?
  3. Are these libraries platform-dependent? I am using gnu gcc 4.6 on Linux at the moment, but ideally it shall be cross-platform. I heard that the definition of "atomic" actually depends on the hardware as well. Can anyone explain that as well?
  4. What's the best way to share a bool variable among multiple threads? I would prefer not to use the "volatile" keyword.

这些代码是否线程安全? / p>

Are these code thread-safe?

double double_m; // double_m is only accessed by current thread.
std::atomic<bool> atomic_bool_x;
atomic_bool_x = true && (double_m > 12.5);

int int_n; // int_n is only accessed by current thread.
std::atomic<int> atomic_int_x;
std::atomic<int> atomic_int_y;
atomic_int_y = atomic_int_x * int_n;


推荐答案

我不是专家或任何东西,我知道:

I'm not an expert or anything, but here's what I know:


  1. std :: atomic $ c> load 和 store (以及一些其他操作)是明确定义的。

  2. 我假设 std :: atomic 是基于 boost :: atomic 。如果可以,使用 std ,否则使用 boost

  3. 两个可移植的, std 完全是这样,但是你的编译器将需要支持C ++ 11

  4. 可能 std :: atomic_bool 。您不应该使用volatile。

  1. std::atomic simply says that calling load and store (and a few other operations) concurrently is well-defined. An atomic operation is indivisible - nothing can happen 'in-between'.
  2. I assume std::atomic is based off of boost::atomic. If you can, use std, otherwise use boost.
  3. They are both portable, with the std being completely so, however your compiler will need to support C++11
  4. Likely std::atomic_bool. You should not need to use volatile.

此外,我相信 load store 不同于 operator = / operator T 只有加载 / 存储是原子

Also, I believe load/store differs from operator=/operator T only load/store are atomic.

不要迷茫。我检查了标准,看起来操作符是以 load / store / etc定义的,但是他们可能返回不同的东西。

Nevermind. I checked the standard and it appears that the operators are defined in terms of load/store/etc, however they may return different things.

进一步阅读:

这篇关于C ++ std :: atomic与Boost原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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