Skip to main content
 首页 » 编程设计

python之导入锁在pypy中不能跨线程工作

2024年08月27日40TianFang

本次测试在python2.6/2.7下通过,在pypy下失败。 pypy 绝对支持线程,并且 imp 锁似乎在没有线程的情况下工作,正如在 pypy 下预期的那样。看起来线程正在获得它自己的导入锁?....

import unittest 
import imp 
import threading 
 
 
class Test(unittest.TestCase): 
 
    def test_import_lock(self): 
        lock_held = threading.Event() 
        test_complete = threading.Event() 
        lock_released = threading.Event() 
 
        def other_thread(): 
            imp.acquire_lock() 
 
            assert imp.lock_held()  # <--- this assertion passes, the imp lock is definitely held 
 
            lock_held.set() 
            test_complete.wait() 
            imp.release_lock() 
 
            lock_released.set() 
 
        t = threading.Thread(target=other_thread) 
        t.setDaemon(True) 
        t.start() 
 
        # Wait until the thread is holding the import lock 
        lock_held.wait() 
 
        # The import lock should be held at this point. The thread even asserted 
        # that it was held! 
        lock_was_held = imp.lock_held() 
 
        # Notify the thread to release the lock 
        test_complete.set() 
 
        # Wait for the lock to be released 
        lock_released.wait() 
 
        # Make sure the lock was held when we expected it to be held 
        assert lock_was_held 
 
if __name__ == '__main__': 
    unittest.main() 

pypy

struys$ python --version 
Python 2.7.6 (394146e9bb67, May 08 2014, 16:45:59) 
[PyPy 2.3.0 with GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] 
struys$ python -m test 
F 
====================================================================== 
FAIL: test_import_lock (__main__.Test) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
  File "test.py", line 42, in test_import_lock 
    assert lock_was_held 
AssertionError 
 
---------------------------------------------------------------------- 
Ran 1 test in 0.001s 
 
FAILED (failures=1) 

python 2.7

struys$ python --version 
Python 2.7.2 
struys$ python test.py 
. 
---------------------------------------------------------------------- 
Ran 1 test in 0.000s 
 
OK 

请您参考如下方法: