2

我写了这个最低限度的代码来解释我的情况:

import threading
import time
import eventlet

eventlet.monkey_patch()

def printing_function():
    while True:
        # here i want to do some work
        print "printing"
        time.sleep(1)

if __name__ == '__main__':
    thread = threading.Thread(target=printing_function)
    thread.start()

    while True:
        # here i want to wait for users input
        raw_input("raw input\n")
        print "inside main loop"
        time.sleep(1)

即使我有 2 个线程,当我调用 raw_input 时它们都被阻塞了。当我注释掉 eventlet.monkey_patch() 时,只有一个线程被阻塞,另一个线程继续打印“打印”。为什么以及我应该怎么做?

4

1 回答 1

2

我想说这里有几点需要注意:

  • raw_input没有被 修补eventlet,所以它的调用被阻塞
  • threading由 修补eventlet,因此线程充当协程

解决此问题的一种方法是避免修补threading,以便线程是真正的线程。为此,您只需要替换:

eventlet.monkey_patch()

和:

eventlet.monkey_patch(os=True,
                     select=True,
                     socket=True,
                     thread=False,
                     time=True)

请注意,何时thread修补True以下模块:thread, threading, Queue.

编辑:如果你想修补threading并有一个 asynchronous raw_input,那么我建议以下实现:

def raw_input(message):
    sys.stdout.write(message)

    select.select([sys.stdin], [], [])
    return sys.stdin.readline()

这将轮询sys.stdin以检查它是否已准备好阅读。如果不是这种情况,它将把控制权交给 eventlet 让其他协程执行。

于 2012-01-27T09:12:14.257 回答