Are Python built-in containers thread-safe?

后端 未结 4 1300
感情败类
感情败类 2020-12-01 09:18

I would like to know if the Python built-in containers (list, vector, set...) are thread-safe? Or do I need to implement a locking/unlocking environment for my shared variab

4条回答
  •  感情败类
    2020-12-01 09:43

    Yes, but you still need to be careful of course

    For example:

    If two threads are racing to pop() from a list with only one item, One thread will get the item successfully and the other will get an IndexError

    Code like this is not thread-safe

    if L:
        item=L.pop() # L might be empty by the time this line gets executed
    

    You should write it like this

    try:
        item=L.pop()
    except IndexError:
        # No items left
    

提交回复
热议问题