Thread-safe atomic operation

Thomas Wouters thomas at xs4all.net
Tue Apr 11 07:51:03 EDT 2000


On Tue, Apr 11, 2000 at 03:02:28PM +0900, Dong-gweon Oh wrote:

> Is there any documents which describe Python's atomic operation in
> multithreaded environment. I guess Python virtual instruction is atomic.
> But, without definitive documentation in high level Python statements, I
> tend to over-lock my programs.

> Are these statements thread-safe?
> 1. import xxx
> 2. xxx = __import__('xxx')
> 3. reload(xxx)
> 4. dict['xxx'] = sys.modules['xxx']
> 5. dict.has_key('xxx')

Well, Python uses a global interpreter lock. This means that no matter howmany
threads are instantiated, only one of them will be executing Python
code. Inside python code, and in C modules and extensions, however, the C
code itself takes care to allow/disallow multiple threads to run a block of
code.

So, the answer to your question is: Yes, all of them are thread-safe, but
none of them will benifit from threading. Some of them may block and allow
threads, though, so you might get *some* aditional performance if you are
doing something else in another thread, at the same time. You can safely
assume all your python code is always thread-safe, and if you do not bother
with the 'Py_BEGIN_ALLOW_THREADS'/'Py_END_ALLOW_THREADS' C macros, so will
all your C extension code (as long as you dont do anything funky with
cloning threads yourself.)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list