I want to release the GIL

Delaney, Timothy (Tim) tdelaney at avaya.com
Tue Oct 21 08:42:12 CEST 2008

Piotr Sobolewski wrote:

> Hello,
> I have such program:
> import time
> import thread
> def f():
>     global lock
>     while True:
>         lock.acquire()
>         print thread.get_ident()
>         time.sleep(1)
>         lock.release()
> lock=thread.allocate_lock()
> thread.start_new_thread(f,())
> thread.start_new_thread(f,())
> time.sleep(60)

1. You should use the threading module.

2. No need for the "global lock" statement here - you're not rebinding the name "lock".

3. These aren't daemon threads, so your program will never exit. You will need to set a flag or something after the time.sleep(60).

> As you can see, I start two threads. Each one works in an infinite
> loop.
> Inside that loop it acquires lock, prints its own id, sleeps a bit and
> then
> releases lock.

4. Because you are holding the lock while sleeping, the other thread does not get the chance to run. Sleeping does not release any locks held.

Instead try something like:

    while True:
        with lock:
            print thread.get_ident()

Note that to use the "with lock:" idiom, you need to be using Python 2.6, or Python 2.5 with a "from __future__ import with_statement".

Tim Delaney

More information about the Python-list mailing list