Using threads in python is safe ?

Benjamin musiccomposition at gmail.com
Sun Mar 16 21:30:54 EDT 2008


On Mar 16, 3:40 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade <smartp... 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/moinor perhaps at the effbot's site  http://www.effbot.org
Even for atomic operations, you should lock, though. That is not
consistent over different Python implementations and is not always
going to be in same in CPython.
>
> > 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