Is python's “in” language construct thread-safe for lists?

半腔热情 提交于 2019-12-08 16:58:51

问题


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

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