python - dummy_threading 有什么作用?

标签 python multithreading python-2.7 python-multithreading

什么时候使用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 相同的行为?

最佳答案

threadthreading 在您的平台上不可用时,可以使用该模块。

您传递给它的函数被同步调用,并且您立即调用了.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/

相关文章:

java - 使用 H2 数据库了解 JdbcConnectionPool

python - 无法在Python中同时运行线程

python - Python代码在C代码中添加const关键字

python - Python语言中 "e"中的 "1e-5"是什么意思,这个表示法的名称是什么?

c# - Python 等效于 C# ADAL AuthenticationContext.AcquireToken

python - 插入操作时 python 和 mysql 的 sql 语法错误

python - 将 CSV 的每一行存储为单独的列表/字典

python - 标签未出现在 Seaborn distplot 中

multithreading - 从多个线程同时从单个串行端口读取和写入

c - 生产者消费者问题