c++ - Thread-safe static variables without mutexing? -
I remember that the static variable declared within the methods is not thread-safe. (As previously mentioned)
dogs * MyClass :: BadMethod () {stable dog ("dog"); Return and dog; }
My Library creates C ++ code for end users to compile as part of their application. The code generated is required to start the stable variable in a thread-safe cross-platform manner. I want to use the boost :: call_once
to mute variable initialization, but then the end users are exposed to the boost dependency.
Is there any way to do this without compromising additional dependence on end-user?
You are right that the static initial thread is not secure (an article on which the compiler turns it on
At present, there is no standard, thread-safe, portable way to make stable standards, double check locking can be used, but you can potentially see non-portable threading libraries ) is required.
If thread protection is essential, then here are some options:
- Do not be lazy (load): Start during static initialization
- Boost Use to give (as you said) or Loki
- If any other static calls its function in the constructor, then this may be a problem. Make your singleton roll on your supported platform (unless you're a threading expert)
- You need access every time. It can be very slow.
Example for 1:
// in a CPP: namespace {dog dog ("vaccines"); } Dogs * MyClass :: BadMethod () {Return and Dogs; }
Example for 4:
dogs * MyClass :: BadMethod () {static scoped_ptr & lt; Dogs & gt; Pdog; {Lock L (Mutex); If (! Pdog.get ()) pdog.reset (new dog ("vaccines")); } Return pdog.get (); }
Comments
Post a Comment