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 variable?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You need to implement your own locking for all shared variables that will be modified in Python. You don’t have to worry about reading from the variables that won’t be modified (ie, concurrent reads are ok), so immutable types (
frozenset,tuple,str) are probably safe, but it wouldn’t hurt. For things you’re going to be changing –list,set,dict, and most other objects, you should have your own locking mechanism (while in-place operations are ok on most of these, threads can lead to super-nasty bugs – you might as well implement locking, it’s pretty easy).By the way, I don’t know if you know this, but locking is very easy in Python – create a threading.lock object, and then you can acquire/release it like this:
In Python 2.5, do
from __future__ import with_statement; Python 2.4 and before don’t have this, so you’ll want to put the acquire()/release() calls intry:...finally:blocks:Some very good information about thread synchronization in Python.