开发者

Is it thread safe to change a variable with no calculation of previous data involved?

开发者 https://www.devze.com 2023-01-29 07:51 出处:网络
I heard it\'s thread unsafe to do \"global_variable += individual_thread_data\"; for example [without locks].

I heard it's thread unsafe to do "global_variable += individual_thread_data"; for example [without locks].

But is it thread safe if one only does "global_variable = individua开发者_C百科l_thread_data" in each thread?


Without considering the variable type, it is not thread safe. You should use mutexes/critical sections or atomic variables.

Sometimes it useful to write a simple code which assigns variables of several types and disassemble it to see how it is going to be assigned.

Also, for a cas-supporting architecture you can use assembler code to simulate an atomic variable.

(Another tip: the variable should be declared as volatile if used in threads, to prevent the optimization done by compiler.)


No, it's just as unsafe (another thread may be using that variable at the same time).

0

精彩评论

暂无评论...
验证码 换一张
取 消