Multithreading with a global variable: if only one thread is changing the variable, is it necessary to lock it?

人走茶凉 提交于 2019-12-24 09:29:00

问题


As titled, several thread accessing one variable, and only one thread will change the variable, and all the others will just read its value. Like this:

Thread 1:

while True:
    a += 1

Thread 2, 3, 4,...:

print a

In this case, only Thread 1 is changing variable a. Will any serious problems happen?

I found a similar C/C++ tagged question titled "in which cases do I need to lock a variable from simultaneous access?", and it seems from the answer, that the only thing I need to worry about is that the a acquired from the other thread might not be as updated.

I'm asking, other than that I might not get the newest a value, is it possible something more serious will happen and crush the code if I don't lock the variable while accessing it?

I don't think this is language related, but if it matters, I'm specifically interested in the case for Python.


回答1:


Generally speaking, how catastrophic a problem it would be would depend on what the consequences were of one of the other threads obtaining the wrong value.

The answer may indeed be computer-language related: See the Software section in the general Wikipedia article on Race condition.

Related to that is the fact that, thanks to the "GIL", for the most part Python programs don't do real multithreading since the interpreter isn't thread-safe.




回答2:


Irrespective of the language, updating a variable by two separate threads will affect the value. But printing the values will not. The only issue is all the threads (2 onwards) will print different values.

Think this is happening in a database. One person can update the dB, but many can read it.



来源:https://stackoverflow.com/questions/43420665/multithreading-with-a-global-variable-if-only-one-thread-is-changing-the-variab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!