+ 1

Need of thread local

Hi I have global variable gi. Each thread tries to access and may result a data race. So value could be 3 or lesser at the end. I do have then atomic and it is thread safe. So value at the end will be 3 for sure. Now , confustion is for thread local. As it is per thread each thread will be having own variable. So, value will be 1 only. Here comes my question as I am confused on thread local. If it is needed per thread, we can have it as function stack variable inside function body. It will also be same thing. So, whats the use of thread local ? https://code.sololearn.com/cay35570Md57/?ref=app

25th Dec 2022, 10:35 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 ответов
+ 2
In your perticular case, it won't matter if the variable was thread_local or a local variable inside function. You would see the difference when your thread calls a function which inturn calls display() function multiple times.
27th Dec 2022, 12:58 AM
Arsenic
Arsenic - avatar
+ 1
Why gi will always be 3 ? If so, we would never need mutex or any locking mechanism...isn't it or i am missing something ?
26th Dec 2022, 8:21 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Thanks Arsenic .. sounds good...facing hard time to think of some example
27th Dec 2022, 6:44 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
FYI in your code gi will always be 3 by the end
26th Dec 2022, 7:54 AM
Raul Ramirez
Raul Ramirez - avatar
0
Locking is very usefu…but in your example your calling the same function so after the 3 joins you basically did a for loop
27th Dec 2022, 6:21 AM
Raul Ramirez
Raul Ramirez - avatar
0
Raul Ramirez , could not agree more. I still feel that gi can be mismanipulated without lock..isnt it ?
27th Dec 2022, 6:45 AM
Ketan Lalcheta
Ketan Lalcheta - avatar