Portable Variables in Linux Programming

I am writing a shared library that will allow related applications to request a resource.

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

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, can call methods on A from different threads.

So my question is how to implement globvar to be thread safe?

I am developing using gcc 4.4.1 on Ubuntu 9.10

+4
source share
3 answers

Wrap your objects to be used in repeat locks, wherever you are. There is C ++ code here that allows you to implement a locking mechanism. Increase Required:

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

Seems pretty cool :)

 LOCK (myObject) { do something with myObject } 

Make sure you review comments to see any corrections that people have made to the code.

+1
source

What about wrapping around a globvar object in a class and providing accessories / mutators that essentially use mutexes? This should give you some thread safety.

+2
source

If you do not need to share globvar between streams, and you do not create gazillion threads, you should also consider using a local storage stream .

The great thing about TLS is that there is no need for mutexes, so blocking does not exist.

0
source

Source: https://habr.com/ru/post/1302183/


All Articles