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?
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:
funcA
could invoke either funcB
or funcC
without honoring the lock that funcA
set.funcA
.In general, NO. Atomic operations are very precisely defined. What you want is a semaphore or a mutex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With