Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic Operations in C++

Tags:

c++

c++11

I have a set of C++ functions:

funcB(){};
funcC(){};
funcA()
{
    funcB();
    funcC();
}

Now I want to make funcA atomic, ie funcB and funcC calls inside funcA should be executed atomically. Is there any way to achieve this?

like image 376
Prabagaran Avatar asked Mar 17 '12 23:03

Prabagaran


2 Answers

One way you can accomplish this is to use the new (C++11) features std::mutex and std::lock_guard.

For each protected resource, you instantiate a single global std::mutex; each thread then locks that mutex, as it requires, by the creation of a 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();
}

Notes:

  • In your example some code unrelated to funcA could invoke either funcB or funcC without honoring the lock that funcA set.
  • Depending upon how your program is structured, you may want to manage the lifetime of the mutex differently. As an example, it might want to be a class member of the class that includes funcA.
like image 168
Robᵩ Avatar answered Sep 30 '22 12:09

Robᵩ


In general, NO. Atomic operations are very precisely defined. What you want is a semaphore or a mutex.

like image 35
Joshua Avatar answered Sep 30 '22 13:09

Joshua