boost-threads: How can I pass a scoped_lock to a callee? - c++

I'm new to the boost threads library. I have a situation where I acquire a scoped_lock in one function and need to wait on it in a callee.
The code is on the lines of:
class HavingMutex
{
public:
...
private:
static boost::mutex m;
static boost::condition_variable *c;
static void a();
static void b();
static void d();
}
void HavingMutex::a()
{
boost::mutex::scoped_lock lock(m);
...
b() //Need to pass lock here. Dunno how !
}
void HavingMutex::b(lock)
{
if (some condition)
d(lock) // Need to pass lock here. How ?
}
void HavingMutex::d(//Need to get lock here)
{
c->wait(lock); //Need to pass lock here (doesn't allow direct passing of mutex m)
}
Basically, in function d(), I need to access the scoped lock I acquired in a() so that I can wait on it. How do I do that ? (Some other thread will notify).
Or can I directly wait on a mutex instead of a lock ?
Any help is appreciated. Thanks !

Pass it by reference:
void HavingMutex::d(boost::mutex::scoped_lock & lock)
{ // ^ that means "reference"
c->wait(lock);
}

Related

Thread safety of nested calls

I have two libs, one is thread safe called class A, The other lib called class B, which used class A to realize functions.
class A {
public:
void Get() {
std::lock_guard<std::mutex> lock(mutex_);
do_something
}
void Put() {
std::lock_guard<std::mutex> lock(mutex_);
do_something
}
private:
std::mutex mutex_;
};
class B {
public:
void Get() {
a.Get();
}
void Put() {
a.Put();
}
private:
A a;
};
So is class B thread safe?
I know that judging whether the thread is safe depends on whether the operation is atomic. If the put operate is not atomic then it's not thread safe. According to the above requirements, I think class B is not an atomic operation, so it is not thread-safe?
When the operation is not atomic, it may not be thread safe. for example we add some operate like below, Is it right?
class B {
public:
void Get() { // But Get is not atomic!!!
do_some_thing(); // atomic
a.Get(); // atomic
do_some_thing(); // atomic
}
void Put() {
do_some_thing();
a.Put();
do_some_thing();
}
private:
A a;
};
Thread safety concerns about the race conditions and data races.
Now, Since the methods of class B don't use any data directly but via delegating other methods in class A that as you said are thread-safe, the methods in B are thread-safe.

Am I implementing a Mutex Lock Class via RAII Properly?

I'm watching a video about mutex and RAII.
In the video the author explains that a good application of RAII (using an object to manage a resource) is a mutex. He has the following class:
class Lock {
private:
Mutext_t* m_pm;
public:
explicit Lock(Mutex_t* pm) { Mutex_lock(pm); m_pm = pm; };
~Lock() { Mutex_unlock(m_pm); };
};
I'm not sure how he implemented Mutex_unlock and Mutex_lock.
My question is: Is the following implementation comparable, and will it achieve the desired result of unlocking a mutex should the function that class object is instantiated in throw an exception?
mutex mu;
class Lock { // Lock will be destroyed if stack is unwound
private:
mutex* p_Mutex;
public:
explicit Lock(mutex* Mutex) {
lock_guard<mutex> u_Lock(*Mutex);
p_Mutex = Mutex;
};
};
void functionB() {
Lock myLock(&mu);
// .. Do stuff that throws an error.
// Unwind stack and destroy myLock, unlocking the mutex?
}
This is very much a simple implementation for learning purposes. Thanks for your help.

Passing mutex reference from main to a class

I need to work with the same mutex and unique_lock across the main function and class instances. However, I am having trouble assigning the mutex/unique_lock address to a class member variable (that is a mutex&).
This is what I have:
Worker.h
class Worker
{
private:
std::mutex &m_mu;
std::unique_lock<std::mutex> &locker;
public:
void start(std::mutex &mu, std::unique_lock<std::mutex> &locker);
};
Worker.cpp
void Worker::start(std::mutex &mu, std::unique_lock<std::mutex> &locker)
{
this->mu = mu; // error
this->locker = locker; // error
}
I tried doing this->mu(mu); but that doesn't work either. Is there anything I can do to make this work?
Thanks.
You need to pass the mutex reference when you construct your class.
Worker::Worker(std::mutex &mu, std::unique_lock<std::mutex> &locker)
:m_mu(mu), locker(locker)
{}
That's the only place you can initialize a reference. Once it's constructed, you cannot change what it references.
Why do you need the locker? The mutex makes the synchronization, the lock is just a RAII object to ease acquiring the mutex.
You don't need to pass the lock object to the function. As long as the class is referring to the correct mutex you can lock the mutex inside the function like this:
class Worker
{
private:
std::mutex& m_mu;
public:
Worker(std::mutex& mu): m_mu(mu) {} // bind reference during initialization
void start();
};
// Worker.cpp
void Worker::start()
{
std::unique_lock<std::mutex> locker(m_mu); // lock the shared resource
// Do something with it here
}
int main()
{
std::mutex mu;
std::vector<Worker> workers(4, Worker(std::ref(mu)));
// etc...
}

Thread safe access to member variable

So I have a class which spawns a thread with the class object as parameter. Then in the thread I call a member function. I use Critical_Sections for synchronizing.
So would that implementation be thread safe? Because only the member is thread safe and not the class object.
class TestThread : public CThread
{
public:
virtual DWORD Work(void* pData) // Thread function
{
while (true)
{
if (Closing())
{
printf("Closing thread");
return 0;
}
Lock(); //EnterCritical
threadSafeVar++;
UnLock(); //LeaveCritical
}
}
int GetCounter()
{
int tmp;
Lock(); //EnterCritical
tmp = threadSafeVar;
UnLock(); //LeaveCritical
return tmp;
}
private:
int threadSafeVar;
};
.
.
.
TestThread thr;
thr.Run();
while (true)
{
printf("%d\n",thr.GetCounter());
}
If the member is your critical section you should only lock the access to it.
BTW, You can implement a Locker like:
class Locker
{
mutex &m_;
public:
Locker(mutex &m) : m_(m)
{
m.acquire();
}
~Locker()
{
m_.release();
}
};
And your code would look like:
mutex myVarMutex;
...
{
Locker lock(myVarMutex);
threadSafeVar++;
}
...
int GetCounter()
{
Locker lock(myVarMutex);
return threadSafeVar;
}
Your implementation is thread safe because you have protected with mutex your access to attribute.
Here, your class is a thread, so your object is a thread. It's what you do in your thread that tell if it is thread safe.
You get your value with a lock/unlock system and you write it with the same system. So your function is thread safe.

custom RAII C++ implementation for scoped mutex locks

I cannot use boost or the latest std::thread library. The way to go is to create a custom implementation of a scoped mutex.
In a few words when a class instance is create a mutex locks. Upon class destruction the mutex is unlocked.
Any implementation available? I don't want to re-invent the wheel.
I need to use pthreads.
resource acquisition is initialization == “RAII”
Note This is an old answer. C++11 contains better helpers that are more platform independent:
std::lock_guard
std::mutex, std::timed_mutex, std::recursive_mutex, std::recursive_timed_mutex
And other options like std::unique_lock, boost::unique_lock
Any RAII tutorial will do.
Here's the gist: (also on http://ideone.com/kkB86)
// stub mutex_t: implement this for your operating system
struct mutex_t
{
void Acquire() {}
void Release() {}
};
struct LockGuard
{
LockGuard(mutex_t& mutex) : _ref(mutex)
{
_ref.Acquire(); // TODO operating system specific
}
~LockGuard()
{
_ref.Release(); // TODO operating system specific
}
private:
LockGuard(const LockGuard&); // or use c++0x ` = delete`
mutex_t& _ref;
};
int main()
{
mutex_t mtx;
{
LockGuard lock(mtx);
// LockGuard copy(lock); // ERROR: constructor private
// lock = LockGuard(mtx);// ERROR: no default assignment operator
}
}
Of course you can make it generic towards mutex_t, you could prevent subclassing.
Copying/assignment is already prohibited because of the reference field
EDIT For pthreads:
struct mutex_t
{
public:
mutex_t(pthread_mutex_t &lock) : m_mutex(lock) {}
void Acquire() { pthread_mutex_lock(&m_mutex); }
void Release() { pthread_mutex_unlock(&m_mutex); }
private:
pthread_mutex_t& m_mutex;
};