+ 5
Multithread and singleton
is c++ have more usage of multiple threads ? can anyone show it on solo learn to check it !? And I heard singleton is no more maintain one object in case of more threads... can anyone guide how to achieve in case of multiple thread as well ? my code for singleton as below : https://code.sololearn.com/cV96i4sHz99T/?ref=app
3 Respuestas
+ 3
Protect it from data races.
Just imagine that 2 thread will increase your counter in the same time. One will rewrite result of other and counter will store wrong value.
You can use std::mutex as simple case.
+ 2
New standard guarantees that static variable is initialized once in multy thread environment.
There was data race at static variable initialization with old compilers.
All other things work in a same order.
Unfortunately, your code provides multiple data races in multy thread case. It means that you can't use your singleton with many threads.
+ 1
Sergey Ushakov could you please let me know what to be done to use this code for many threads as singleton?