I want to release the GIL

Carl Banks pavlovevidence at gmail.com
Tue Oct 21 19:55:56 CEST 2008


On Oct 21, 7:49 am, MRAB <goo... at mrabarnett.plus.com> wrote:
> On Oct 21, 10:22 am, Carl Banks <pavlovevide... at gmail.com> wrote:
>
> > On Oct 21, 5:09 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> > wrote:
>
> > > En Tue, 21 Oct 2008 04:58:00 -0200, Piotr Sobolewski  
> > > <piotr_sobolew... at o2.pl> escribió:
>
> > > > But what about my main question? Is it possible to release GIL without
> > > > sleeping? I know that in this example situation I can achieve my goals
> > > > without that - I can just move sleep outside of locked block. But I
> > > > just want to know it for future - can I just do something like
> > > > thread.gil_release()?
>
> > > No, you can't release the GIL *and* continue executing Python code.
>
> > I don't think that's what the OP was asking about; I think he merely
> > wanted to force a GIL release to give the other thread a chance to
> > run.
>
> > Reason being: in his code the lock was re-acquired right after it was
> > released.  This meant that the same thread that released the lock
> > almost always acquired it right back, since there was only a tiny
> > window in which a thread switch could take place.  Obviously the
> > wisdom of what he was doing was suspect, but the OP was right in that
> > a manual GIL release would allow a thread switch and could have helped
> > avoid starvation in that case.
>
> If he released the GIL then he would still have to ensure that other
> thread got a chance to claim it before the releaser tried to reclaim
> it,

I'm pretty sure you're right.  The other thread has to acquire both
the shared lock and the GIL before it can run, and in that order.  So,
even if you were to release the GIL manually after releasing the lock,
it won't help unless the underlying thread scheduler had already done
a thread switch so that the other thread could get the shared lock.

However, even if the other thread manages to acquire the lock in the
tiny window, it wouldn't need a manual GIL release since the original
thread will block as soon as it tries to re-acquire the lock.

IOW, just releasing the GIL does nothing.

So I goofed.  Sorry bout that.  Scratch was I said in the previous
post.


> which suggests the sleep that he was trying to avoid (unless the
> release was really "yield the GIL to another thread if one is waiting
> for it").

Right, but it isn't.


Carl Banks



More information about the Python-list mailing list