Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a thread safe way to initialize a [ThreadStatic]?

Tags:

People also ask

How does ThreadStatic work?

Remarks. A static field marked with ThreadStaticAttribute is not shared between threads. Each executing thread has a separate instance of the field, and independently sets and gets values for that field. If the field is accessed on a different thread, it will contain a different value.

How to make a function thread safe in c++?

This can be fixed by adding a mutex that demands that two threads cannot run the run member simultaneously. See Boost. Thread for a good mutex example. Please include an example to clarify that a const (read-only) function also needs mutex protection if another function may write to the data member at the same time.

What is thread safe in c++?

An object is thread-safe for reading from multiple threads. For example, given an object A, it is safe to read A from thread 1 and from thread 2 simultaneously. If an object is being written to by one thread, then all reads and writes to that object on the same or other threads must be protected.


[ThreadStatic]
private static Foo _foo;

public static Foo CurrentFoo {
   get {
     if (_foo == null) {
         _foo = new Foo();
     }
     return _foo;
   }
}

Is the previous code thread safe? Or do we need to lock the method?