]> granicus.if.org Git - python/commitdiff
Issue #7205: Fix a possible deadlock when using a BZ2File object from several threads...
authorAntoine Pitrou <solipsis@pitrou.net>
Tue, 27 Oct 2009 17:41:58 +0000 (17:41 +0000)
committerAntoine Pitrou <solipsis@pitrou.net>
Tue, 27 Oct 2009 17:41:58 +0000 (17:41 +0000)
Lib/test/test_bz2.py
Misc/NEWS
Modules/bz2module.c

index 215a04e99c94b209e94a83b126383cba06fb9a3b..f68586dee24c9121c8fafdb651a1214744d79f26 100644 (file)
@@ -7,6 +7,7 @@ from cStringIO import StringIO
 import os
 import subprocess
 import sys
+import threading
 
 bz2 = import_module('bz2')
 from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor
@@ -306,6 +307,23 @@ class BZ2FileTest(BaseTest):
         else:
             self.fail("1/0 didn't raise an exception")
 
+    def testThreading(self):
+        # Using a BZ2File from several threads doesn't deadlock (issue #7205).
+        data = "1" * 2**20
+        nthreads = 10
+        f = bz2.BZ2File(self.filename, 'wb')
+        try:
+            def comp():
+                for i in range(5):
+                    f.write(data)
+            threads = [threading.Thread(target=comp) for i in range(nthreads)]
+            for t in threads:
+                t.start()
+            for t in threads:
+                t.join()
+        finally:
+            f.close()
+
 
 class BZ2CompressorTest(BaseTest):
     def testCompress(self):
index 6d487145ac3b3835c8f7f12ae9122223e19293fd..1ee755791a72798cb5499ce28d06e593da530271 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -427,6 +427,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #7205: Fix a possible deadlock when using a BZ2File object from
+  several threads at once.
+
 - Issue #7071: byte-compilation in Distutils is now done with respect to
   sys.dont_write_bytecode.
 
index 045d7b270c03d890741971465dcca907735ff468..c3dae7a671eba8b5ff25bf0c0f7a3d5fdeceb426 100644 (file)
@@ -78,7 +78,12 @@ typedef fpos_t Py_off_t;
 
 
 #ifdef WITH_THREAD
-#define ACQUIRE_LOCK(obj) PyThread_acquire_lock(obj->lock, 1)
+#define ACQUIRE_LOCK(obj) do { \
+       if (!PyThread_acquire_lock(obj->lock, 0)) { \
+               Py_BEGIN_ALLOW_THREADS \
+               PyThread_acquire_lock(obj->lock, 1); \
+               Py_END_ALLOW_THREADS \
+       } } while(0)
 #define RELEASE_LOCK(obj) PyThread_release_lock(obj->lock)
 #else
 #define ACQUIRE_LOCK(obj)