Reputation: 5701
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
Upvotes: 4
Views: 912
Reputation: 15327
If you do not need to share globvar between threads and you aren't spawning a gazillion threads, you should also consider using thread-local storage.
The great thing about TLS is, there is no need for mutexes, so there is no blocking.
Upvotes: 0
Reputation: 22721
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.
Upvotes: 1
Reputation: 111120
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.
Upvotes: 2