开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜