Boost logo

Boost Users :

From: Nat Goodspeed (nat_at_[hidden])
Date: 2008-07-12 09:40:24


Adam Nielsen wrote:

> Basically I have a handful of objects, and they all use a shared
> resource (a C-style function.) The function isn't thread-safe, so I
> want to protect it to ensure only one thread at a time can call it.
>
> My idea was to create a mutex for this (lock before the call, unlock
> after it)...
> I tried passing around references to the mutex ...
>
> Should I be using boost::mutex for this? How would you normally
> serialise access among different objects like this? I'm finding the
> examples somewhat tricky to work from, as most of them use global
> variables and C-style functions for creating threads, which doesn't
> really fit with the C++ model of my program - I could just make the
> mutex a global variable but it doesn't seem like the cleanest solution
> to me.

I think I'd probably create a class to manage access to the shared
function. The class would contain the mutex, and the method that calls
the C function would instantiate the lock object. Nobody else would
directly call the C function any more.

That approach generalizes to a family of related functions, plus
whatever persistent data they might need.

There are a couple of different ways to instantiate the wrapper class.
One is to use the Singleton pattern. Note that Boost accepted a
Singleton library a couple months ago, which hasn't yet made it into an
official Boost release; check the vault for the current version.
Singleton is essentially a global with a bit of protection. But that
might be an acceptable way to manage a global resource (your C function).

Since you already have a way to pass mutex references to your handful of
objects, though, you could pass a reference to your wrapper object
instead. But then you have to figure out where the shared wrapper object
lives, and who's responsible for its lifespan.

I'd probably allocate it on the heap, pointing to it with a
boost::shared_ptr. Store a copy of that boost::shared_ptr in each of
your handful of objects. Ownership is shared among them, and the last
one to leave turns out the lights.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net