什么时候使用dummy_threading
?
我原以为它可能会用模拟线程替换系统级线程,以防系统级线程对 Python 不可用。
但是当我运行这个时:
import dummy_threading as threading
semaphore = threading.Semaphore()
def f(i):
semaphore.acquire()
print i
for i in xrange(10):
threading.Thread(target=f, args=(i,)).start()
for _ in xrange(10):
semaphore.release()
我得到 0
,并且程序没有终止。不仅如此,Python 还莫名其妙地继续吞噬我计算机的内存,直到它一无所有。
当我运行这个时:
import threading
semaphore = threading.Semaphore()
def f(i):
semaphore.acquire()
print i
for i in xrange(10):
threading.Thread(target=f, args=(i,)).start()
for _ in xrange(10):
semaphore.release()
我按预期得到 0 1 3 5 7 9 2 4 6 8
。
我一定是误解了dummy_threading
。我什么时候使用它?
仅供引用,我在 Windows 7 和 Fedora 18 上进行了比较,结果相同。
编辑:然而,以下给出了 0 1 2 3 4 5 6 7 8 9
:
import dummy_threading as threading
event = threading.Event()
def f(i):
event.wait()
print i
for i in xrange(10):
threading.Thread(target=f, args=(i,)).start()
event.set()
最大的问题是:dummy_threading
做什么,或者什么时候它会给出与 threading
相同的行为?
最佳答案
当 thread
和 threading
在您的平台上不可用时,可以使用该模块。
您传递给它的函数被同步调用,并且您立即调用了.start()
。第一个函数获取信号量,打印,然后调用第二个函数并阻塞。它同步运行并且永不返回。
来自dummy_thread
documentation :
Be careful to not use this module where deadlock might occur from a thread being created that blocks waiting for another thread to be created. This often occurs with blocking I/O.
来自EFF-bot post (否则很短并且缺少工作链接):
Helpers to make it easier to write code that use threads where supported, but still runs on Python versions without thread support. The dummy modules simply run the threads sequentially.
注意让它变得更容易部分;如果没有实际的线程,您不能期望在 dummy_threading
下运行的代码不会像您的示例中那样死锁。
关于python - dummy_threading 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134017/