Rella
Rella

Reputation: 66935

Boost::mutex - is it possible to lock it inside one class function and unlock on another?

So we have class with functions a and b. Thread one calls a and no other thread can call a or b untill one would call b. Meaning thread one would be capable to call a and than a and ... and than a, and while one had not called b other threads that want to call a or b stand waiting. is it possible to do such thing with boost::mutex and how to do it?

Upvotes: 2

Views: 2095

Answers (4)

James Kanze
James Kanze

Reputation: 153909

The mutex is not a problem; it's the lock. The simplest solution is just to call mutex::lock() and mutex::unlock() manually, and forget about the mutex::scoped_lock; after all, you don't want the lock to respect scope. The problem with this is the usual one; you probably want to free the lock in case of an exception. One solution would be to allocate the mutex::scoped_lock dynamically, and use a std::auto_ptr or a boost::shared_ptr to manage it. (Curiously enough, neither boost::mutex::scoped_lock nor std::lock_guard are movable, so you need dynamic allocation in order to transfer ownership.)

Upvotes: 6

rodrigo
rodrigo

Reputation: 98348

It is possible. Just call boost::mutex::lock() from a and boost::mutex::unlock() from b.

But note that in the case of an exception thrown while the mutex is locked you should ensure that unlock is called eventually. And scoped_lock does that automatically, but you'll have to do it manually.

Upvotes: 1

Pedro Ferreira
Pedro Ferreira

Reputation: 860

There are several ways to do it. Either you have your mutex as an attribute of a base class and then inherit your working objects from it. Or else send a reference of the mutex to each working class.

Upvotes: 2

Nim
Nim

Reputation: 33655

It has separate lock() and unlock() functions. Make the mutex a member of your class, and then call these respective functions... I would find an alternative approach though - you could have all sorts of odd situations (say thread calling a crashes?)

Upvotes: 3

Related Questions