Unfortunately, I believe that the only way to avoid this is to use non-portable one-time initialization directives and not destroy the lock at all. You need to solve two main problems:
- What happens if two threads start accessing the lock for the first time? [those. you cannot be lazy, create a lock]
- What happens if the lock is destroyed too soon? [that is, you cannot statically create a lock]
The combination of these restrictions forces you to use an intolerable mechanism to create a lock.
In pthreads, the easiest way to handle this is with PTHREAD_MUTEX_INITIALIZER , which allows you to statically initialize locks:
class LibLoader{ static pthread_mutex_t mutex;
In windows you can use synchronous one-time initialization .
Alternatively, if you can guarantee that there will be only one thread before the main launches, you can use a singleton pattern without breaking and just force the lock to touch before main ():
class LibLoader { class init_helper { init_helper() { LibLoader::getLock(); } }; static init_helper _ih; static Lock *_theLock; static Lock *getLock() { if (!_theLock) _theLock = new Lock(); return _theLock; }
Note that this makes it impossible for the hypothetical (but most likely true) assumption that static objects of type POD will not be destroyed until all static objects other than POD are destroyed. I do not know any platform in which this is not so.
source share