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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With