diff -r 088e5d705171 Include/pythread.h
--- a/Include/pythread.h Sat May 14 14:19:56 2011 +0200
+++ b/Include/pythread.h Sat May 14 20:29:39 2011 +0200
@@ -84,6 +84,7 @@
PyAPI_FUNC(void) PyThread_delete_key_value(int key);
/* Cleanup after a fork */
+PyAPI_FUNC(void) PyThread_ReInitLocks(void);
PyAPI_FUNC(void) PyThread_ReInitTLS(void);
#ifdef __cplusplus
diff -r 088e5d705171 Lib/test/lock_tests.py
--- a/Lib/test/lock_tests.py Sat May 14 14:19:56 2011 +0200
+++ b/Lib/test/lock_tests.py Sat May 14 20:29:39 2011 +0200
@@ -3,6 +3,7 @@
"""
import sys
+import os
import time
from _thread import start_new_thread, get_ident, TIMEOUT_MAX
import threading
@@ -286,6 +287,66 @@
self.assertFalse(lock._is_owned())
+class LockAfterForkTests(BaseTestCase):
+ """
+ Tests that standard and internal locks (e.g. I/O) are correctly
+ re-initialized after fork.
+ """
+
+ def test_lock_after_fork(self):
+ lock = self.locktype()
+ lock.acquire()
+ pid = os.fork()
+ if pid == 0:
+ # the lock should be re-initialized
+ for i in range(5):
+ lock.acquire()
+ lock.release()
+ os._exit(0)
+ else:
+ lock.release()
+ os.waitpid(pid, 0)
+
+ def test_lock_after_fork_from_thread(self):
+ # same thing, but with a lock acquired from another thread
+ lock = self.locktype()
+ def f():
+ lock.acquire()
+ b = Bunch(f, 1)
+ b.wait_for_finished()
+ pid = os.fork()
+ if pid == 0:
+ # the lock should be re-initialized
+ lock.acquire()
+ lock.release()
+ os._exit(0)
+ else:
+ lock.release()
+ os.waitpid(pid, 0)
+
+ def test_iolock_after_fork(self):
+ r, w = os.pipe()
+ rf = os.fdopen(r)
+ def f():
+ # this will block with the file's lock held
+ rf.read(1)
+ b = Bunch(f, 1)
+ time.sleep(0.1)
+ # fork while the file's lock is held, and close the write-end so that
+ # the thread and child process receive EOF
+ pid = os.fork()
+ os.close(w)
+ if pid == 0:
+ # the file's lock should be reinitialized, should get EOF
+ rf.read(1)
+ rf.close()
+ os._exit(0)
+ else:
+ b.wait_for_finished()
+ rf.close()
+ os.waitpid(pid, 0)
+
+
class EventTests(BaseTestCase):
"""
Tests for Event objects.
diff -r 088e5d705171 Lib/test/test_threading.py
--- a/Lib/test/test_threading.py Sat May 14 14:19:56 2011 +0200
+++ b/Lib/test/test_threading.py Sat May 14 20:29:39 2011 +0200
@@ -713,6 +713,10 @@
class CRLockTests(lock_tests.RLockTests):
locktype = staticmethod(threading._CRLock)
+@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
+class LockAfterForkTests(lock_tests.LockAfterForkTests):
+ locktype = staticmethod(threading.Lock)
+
class EventTests(lock_tests.EventTests):
eventtype = staticmethod(threading.Event)
@@ -734,7 +738,8 @@
def test_main():
- test.support.run_unittest(LockTests, PyRLockTests, CRLockTests, EventTests,
+ test.support.run_unittest(LockTests, PyRLockTests, CRLockTests,
+ LockAfterForkTests, EventTests,
ConditionAsRLockTests, ConditionTests,
SemaphoreTests, BoundedSemaphoreTests,
ThreadTests,
diff -r 088e5d705171 Modules/_threadmodule.c
--- a/Modules/_threadmodule.c Sat May 14 14:19:56 2011 +0200
+++ b/Modules/_threadmodule.c Sat May 14 20:29:39 2011 +0200
@@ -322,7 +322,10 @@
r = acquire_timed(self->rlock_lock, microseconds);
}
if (r == PY_LOCK_ACQUIRED) {
- assert(self->rlock_count == 0);
+ if (self->rlock_count != 0) {
+ PyErr_SetString(ThreadError, "couldn't acquire lock");
+ return NULL;
+ }
self->rlock_owner = tid;
self->rlock_count = 1;
}
@@ -393,11 +396,10 @@
r = PyThread_acquire_lock(self->rlock_lock, 1);
Py_END_ALLOW_THREADS
}
- if (!r) {
+ if (!r || self->rlock_count != 0) {
PyErr_SetString(ThreadError, "couldn't acquire lock");
return NULL;
}
- assert(self->rlock_count == 0);
self->rlock_owner = owner;
self->rlock_count = count;
Py_RETURN_NONE;
diff -r 088e5d705171 Modules/signalmodule.c
--- a/Modules/signalmodule.c Sat May 14 14:19:56 2011 +0200
+++ b/Modules/signalmodule.c Sat May 14 20:29:39 2011 +0200
@@ -1234,6 +1234,7 @@
PyOS_AfterFork(void)
{
#ifdef WITH_THREAD
+ PyThread_ReinitLocks();
_PyGILState_Reinit();
PyEval_ReInitThreads();
main_thread = PyThread_get_thread_ident();
diff -r 088e5d705171 Python/thread_pthread.h
--- a/Python/thread_pthread.h Sat May 14 14:19:56 2011 +0200
+++ b/Python/thread_pthread.h Sat May 14 20:29:39 2011 +0200
@@ -1,6 +1,31 @@
/* Posix threads interface */
+/*
+ * Note on the interaction between locks and fork.
+ * After fork, POSIX explicitly states that mutexes and other synchronization
+ * primitives are unusable in the child process. This can trigger random
+ * deadlocks and even segfaults in rare cases.
+ * To mitigate this issue, PyThread_ReinitLocks is called by PyOS_AfterFork and
+ * re-initializes locks so that they are usable in the child process.
+ * Notes:
+ * - This only applies to raw locks, i.e. locks allocated directly through
+ * PyThread_allocate_lock, such as threading.Lock and locks used in C code
+ * (e.g. I/O code). This doesn't solve the problem for higher-level
+ * synchronization primitives such as Condition and Event (those could
+ * probably be handled by a pthread_atfork-like mechanism invoked by
+ * PyOS_AfterFork).
+ * - pthread_mutex_destroy/pthread_cond_destroy/sem_destroy are not called in
+ * PyThread_reinit_lock. This is done on purpose, because those calls are
+ * unsafe after fork (deadlocks experienced on Linux with NPTL). So we just
+ * call pthread_mutex_init/pthread_cond_init/sem_init. This should normally
+ * not leak resources, but even if it does, it's better than a deadlock.
+ * - The linked list of locks (locks_head) doesn't need to be protected from
+ * concurrent access because locks are created/destroyed with the GIL held,
+ * and PyThread_ReinitLocks is called after fork, so there's only one running
+ * thread at that point.
+*/
+
#include