Using threads in python is safe ?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Mar 16 16:40:42 EDT 2008


En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade <smartpawn at gmail.com>  
escribi�:

> I want to use therads in my application. Going through the docs , I read
> about GIL.
> Now I am confused whether using threads in python is safe or not.
>
> One thing I know that if I am accessing global variables in two or more
> threads I need to synchronize them
> using locking or such mechanism so that only one thread access them at a
> time.

Yes, altough some operations are known to be atomic so you don't need a  
lock in that cases. I think there is a list in the wiki somewhere  
http://wiki.python.org/moin or perhaps at the effbot's site  
http://www.effbot.org

> 1.  In order to support multi-threaded Python programs, there's a global
> lock that must be held
> by the current thread before it can safely access Python objects.
> Does this lock need to be held by python application script expliciltly
> before accessing any python object or
> interpreter takes acre of it ?

No, the interpreter takes care of it. The GIL is a concern for those  
writing extensions using the Python API.

> 2. Does multithreaded python script need to held lock before calling any
> blocking I/O call?
> Or one should not worry about GIL while using python threads if job to be
> processed by thread does not call
> any global variables and thread unsafe Python/C extension ?

Python code should not worry about the GIL. The problem would be, a  
callback written in Python for a not-thread-aware extension that had  
released the GIL.

-- 
Gabriel Genellina




More information about the Python-list mailing list