Python GIL and threads synchronization

After having read various articles that explain GIS and threads in Python, and Are locks unnecessary in multi-threaded Python code because of the GIL? which is a very useful answer, I have one "last question".

If, ideally, my threads only operate on shared data through atomic (Python VM) instructions, eg appending an item to a list, a lock is not needed, right?


That really depends on your application. You may need locks for your specific use case just like in any other language, but you don't need to protect the python objects getting corrupted anyway. In that sense you don't need locks.

Here's an example that uses a bunch of pretty much atomic operations, but can still behave in unexpected ways when you combine them.

Thread 1:

v = l[-1]
DoWork(v]
del l[-1]

Thread 2:

l.append(3)

If Thread 2 runs in between the first and last statement of Thread 1, then Thread 1 just deleted the wrong work item. None of the python objects are corrupt or anything, but you still got an unexpected result, and potentially exceptions could be thrown.

If you have shared data structures, you usually need to protect them with locks, or even better use already written protected versions, like in this case maybe a Queue: http://docs.python.org/library/queue.html


理论上不是,但它取决于逻辑,例如,当你维持秩序时你需要一个锁。


When you share data between threads, you should always make sure your data is properly synchronized because you cannot rely on wether operations will be or not atomic in the future.

It is easier to get the multi-threading design right in the first place than try to fix something that breaks because of a change in implementation or a wrong assumption.

链接地址: http://www.djcxy.com/p/86466.html

上一篇: PyPy vs Cpython,会不会放弃GIL并支持POSIX线程?

下一篇: Python GIL和线程同步