问题
Is obj in a_list
thread-safe while a_list
might be modified in a different thread?
Here's a comprehensive yet non-exhaustive list of examples of list
operations and whether or not they are thread safe, however I couldn't find any reference for the in
language construct.
In terms of python implementation, I use CPython, but answers re other implementations would be helpful too for the community.
回答1:
I am assuming you are using CPython here.
Provided there is no custom __contains__
or __iter__
hook dropping back into Python or the values you test against contained in the list use custom __eq__
hooks implemented in Python code, the in
operator can be handled entirely in C, and is just one opcode.
This makes the operation entirely thread-safe; Python threads only switch between opcodes; the GIL (global interpreter lock) normally only unlocks between opcodes.
That said, if you use in
on a custom C type that unlocks the GIL when testing containment would not be thread-safe.
In other words: the in
bytecode test is locked, but if the operator needs to call Python code (through __contains__
, iterating with __iter__
when no __contains__
implementation is available, or the values are test against __eq__
hooks implemented in Python), then the operation is not thread safe.
For other Python implementations, how threading is handled can vary widely. Certainly, Jython and IronPython have no GIL, and you should assume the operation is not thread safe.
来源:https://stackoverflow.com/questions/19727759/is-pythons-in-language-construct-thread-safe-for-lists