[New-bugs-announce] [issue7242] Forking in a thread raises RuntimeError

Zsolt Cserna report at bugs.python.org
Fri Oct 30 11:58:02 CET 2009

New submission from Zsolt Cserna <zsolt.cserna at morganstanley.com>:

Python 2.6.4 (r264:75706, Oct 29 2009, 12:00:12) [C] on sunos5

On my sunos5 system if I call os.fork() in a thread created by
thread.start_new_thread(), it raises RuntimeError with the message 'not
holding the import lock'. It's a vanilla python compiled on sunos5 with
suncc. In 2.6.3 it's ok, I think this issue is caused by patch located
at http://codereview.appspot.com/96125/show.

The problem can be re-produced by running the script attached.

I've looked into the source and it seems to me the following:

Based on the the change above, it calls fork1() system call between a
lock-release calls:

3635 » _PyImport_AcquireLock();
3636 » pid = fork1();
3637 » result = _PyImport_ReleaseLock();

_PyImport_ReleaseLock is called in both the child and parent. Digging
more into the code, _PyImport_ReleaseLock starts with the following:

        long me = PyThread_get_thread_ident();
        if (me == -1 || import_lock == NULL)
                return 0; /* Too bad */
        if (import_lock_thread != me)
                return -1;

In the above code, if I interpret correctly, it compares the result of
the current thread id returned by PyThread_get_thread_ident call with
the thread id of the thread holding the lock - if it's different then
the current thread cannot release the lock because it's not owned by it.

Based on my results on solaris the 'me' variable will be different in
the parent and in the child (in parent it remains the same) - resulting
that the child thinks that it's not holding the release lock.

I'm using pthreads on both linux and solaris. On linux the code above is
working fine, but on solaris it behaves differently.

components: Library (Lib)
files: thread_test.py
messages: 94701
nosy: csernazs
severity: normal
status: open
title: Forking in a thread raises RuntimeError
type: behavior
versions: Python 2.6
Added file: http://bugs.python.org/file15232/thread_test.py

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list