Overview
Features
Download
Documentation
Community
Add-Ons & Services

Mutex factory to avoid static initialization problems?

A general discussion forum.

Mutex factory to avoid static initialization problems?

Postby amattice » 27 Jul 2011, 19:55

I find it common to need a mutex defined in global space that may be used across modules, extern in one module and defined in a separate module so the two modules can share the same synchronization key for controlling access to various resources or functions.

In doing so, I sometimes fall prey to the problem of the "Lazy static initialization order fiasco."

Microsoft's compilers seem to be very good an unwinding the complexity of static initialization of global objects, but not so in GCC. So where I used the Poco::Mutex class through a global variable things were fine in my Windows compilation but when catching up in GCC those same global mutexes ended up being used before they were initialized, resulting in various failures when the mutexes were consumed by Poco::ScopedLock.

The fix was to manage the globabally declared mutexes by wrapping them in a singleton class so I could call a factory method like "GetInstance" which returns a reference to the managed mutex... and that's just enough to cause the mutex to initialize. A similar concept exists in the Poco::Logger class where a reference can be retrieved in global scope which doesn't suffer from "static initialization order" issues, but I have multiple differently named global singleton classes to keep the intentionally separate mutexes separated.

Adding a local-module wrapper around Poco::Mutex to retrieve the reference and force static initialization does the trick (initializes when retrieving the reference), but I would imagine other Poco users might run into the same problem since mutexes are often declared in global scope when adding thread insulation to old projects or non OO code.

Would it be useful to extend the Poco::Mutex class (and siblings) with a factory as part of the class or a global factory function to force initialization when retrieving the reference? (i.e. "GetInstance")

Maybe the "Tips & Tricks" section would be the right place for an example demonstrating how to use something like Poco::Singleton to manage statically initialized global mutexes? (if that's a nice way to handle the problem rather than building a solution into the library)

Andy
amattice
 
Posts: 1
Joined: 27 Jul 2011, 19:43

Return to General Discussion

Who is online

Users browsing this forum: No registered users and 3 guests

cron