Pau*_*per 3 python multithreading python-multithreading python-2.7
我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()
Run Code Online (Sandbox Code Playgroud)
我得到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()
Run Code Online (Sandbox Code Playgroud)
我得到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()
Run Code Online (Sandbox Code Playgroud)
最大的问题是:做dummy_threading 什么,或者什么时候它会给出与threading?
该模块意味着要使用时thread,并threading没有您的平台上。
你传递给它的函数被同步调用,你.start()立即调用。第一个函数获取信号量,打印,然后调用第二个函数并阻塞。它同步运行并且永不返回。
小心不要使用这个模块,因为正在创建的线程可能会发生死锁,阻塞等待另一个线程的创建。这通常发生在阻塞 I/O 中。
和来自EFF-bot 的帖子(否则很短并且缺少工作链接):
帮助程序可以更轻松地编写使用受支持线程的代码,但仍然可以在没有线程支持的 Python 版本上运行。虚拟模块只是按顺序运行线程。
注意让它更容易的部分;没有实际线程,您不能期望在其下运行的代码dummy_threading不会像您的示例中那样死锁。
| 归档时间: |
|
| 查看次数: |
5210 次 |
| 最近记录: |