views:

120

answers:

2

I am writing a shared library that will allow linked applications to query a resource.

The resource class is implemented with only static methods (see below). It also uses a global object (well scoped in an anonymous namespace). The reason for the global variable is that I do not want to expose users of the library to the internals of the system. I suppose I could have used a pimpl idiom, but that still does not address the issue of thread safety.

The class looks something like this:

//Header
class A
{
  public:
     static int foo();
     static double foobar();
};


// Source
namespace
{
   SomeResourceObject globvar;  // <- how can this variable be made thread safe ?
}

int A::foo(){}
double A::foobar(){}

Some of the applications using this library will be multithreaded and thus may call methods on A from different threads.

My question therefore is how to implement globvar so as to be threadsafe?

I am developing using gcc 4.4.1 on Ubuntu 9.10

+2  A: 

How about wrapping up the globvar object in a class and providing accessors/mutators which inherently use mutexes? That ought to give you some thread safety.

dirkgently
+1  A: 

Wrap your objects to be operated upon in re-entrant locks wherever you access it :) There's some code in C++ here which allows you to implement a locking mechanism. Needs Boost though:

http://the-lazy-programmer.com/blog/?p=39

Seems quite cool :)

LOCK (myObject) {
    do something with myObject
}

Make sure you look at the comments to see any fixes people have made to the code.

Chris Dennett
Yup, I think this will do the trick. I am using boost threads already in my code, so this works well for me. Thanks
Stick it to THE MAN