jeudi 21 février 2019

Synchronize 2 member functions using C++11 features

We have two member functions: a() and b() of a class

There is only one main thread and we want that when member method a() is executing call to b() member method from some other flow should wait until a() execution is over and vice versa. Hence below restrictions needs to be applied:

a() and b() method should not execute together at any same time

How to code it using C++11 features?

Since I am not familiar with C++11 features will the below implementation work:

#include <mutex>
#include <thread>

std::mutex a_lock;

void a() 
{
    std::lock_guard<std::mutex> lock(a_lock);
}

void b()
{
    std::lock_guard<std::mutex> lock(a_lock);

}

Aucun commentaire:

Enregistrer un commentaire