Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:
L[0] += 1
is not guaranteed to actually increase L[0] by one if another thread does the same thing, because +=
is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.
To clarify a point in Thomas' excellent answer, it should be mentioned that append()
is thread safe.
This is because there is no concern that data being read will be in the same place once we go to write to it. The append()
operation does not read data, it only writes data to the list.
Here's a comprehensive yet non-exhaustive list of examples of list
operations and whether or not they are thread safe.
Hoping to get an answer regarding the obj in a_list
language construct here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With