+ 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

14th Sep 2018, 5:57 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
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.
15th Sep 2018, 4:39 AM
Sergey Ushakov
Sergey Ushakov - avatar
+ 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.
14th Sep 2018, 7:39 PM
Sergey Ushakov
Sergey Ushakov - avatar
+ 1
Sergey Ushakov could you please let me know what to be done to use this code for many threads as singleton?
15th Sep 2018, 12:53 AM
Ketan Lalcheta
Ketan Lalcheta - avatar