C++中的原子操作

Pra*_*ran 6 c++ c++11

我有一组C++函数:

funcB(){};
funcC(){};
funcA()
{
    funcB();
    funcC();
}
Run Code Online (Sandbox Code Playgroud)

现在,我想使funcA原子,即funcBfuncC调用内funcA应自动执行.有没有办法实现这个目标?

Rob*_*obᵩ 11

一种方法是使用新的(C++ 11)功能std::mutexstd::lock_guard.

对于每个受保护资源,您实例化一个全局std::mutex; 然后,每个线程根据需要通过创建一个锁定该互斥锁std::lock_guard:

#include <thread>
#include <iostream>
#include <mutex>
#include <vector>

// A single mutex, shared by all threads. It is initialized
// into the "unlocked" state
std::mutex m;

void funcB() {
  std::cout << "Hello ";
}
void funcC() {
  std::cout << "World." << std::endl;
}
void funcA(int i) {

  // The creation of lock_guard locks the mutex
  // for the lifetime of the lock_guard
  std::lock_guard<std::mutex> l(m);

  // Now only a single thread can run this code
  std::cout << i << ": ";
  funcB();
  funcC();

  // As we exit this scope, the lock_guard is destroyed, 
  // the mutex is unlocked, and another thread is allowed to run
}

int main () {
  std::vector<std::thread> vt;

  // Create and launch a bunch of threads
  for(int i =0; i < 10; i++)
    vt.push_back(std::thread(funcA, i));

  // Wait for all of them to complete
  for(auto& t : vt)
    t.join();
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 在您的示例中,一些与之无关的代码funcA可以调用funcBfuncC不调用funcA设置的锁.
  • 根据程序的结构,您可能希望以不同方式管理互斥锁的生命周期.例如,它可能希望成为包含的类的类成员funcA.


Jos*_*hua 6

一般来说,NO.非常精确地定义了原子操作.你想要的是信号量或互斥量.