Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将来包装队列_Python_Asynchronous_Concurrency_Multiprocessing_Tornado - Fatal编程技术网

Python 将来包装队列

Python 将来包装队列,python,asynchronous,concurrency,multiprocessing,tornado,Python,Asynchronous,Concurrency,Multiprocessing,Tornado,我正在用Python 3.7编写一个Tornado Web服务器,以显示多处理库运行的进程的状态 下面的代码可以工作,但我希望能够使用Tornado的内置库而不是在线程库中进行黑客攻击。我还没有弄明白如何在排队时不阻止龙卷风。我认为正确的解决方案是在将来的某个时候包装get调用。我已经试了好几个小时了,但还不知道怎么做 在我的多处理脚本中: class ProcessToMonitor(multiprocessing.Process) def __init__(self): multi

我正在用Python 3.7编写一个Tornado Web服务器,以显示多处理库运行的进程的状态

下面的代码可以工作,但我希望能够使用Tornado的内置库而不是在线程库中进行黑客攻击。我还没有弄明白如何在排队时不阻止龙卷风。我认为正确的解决方案是在将来的某个时候包装get调用。我已经试了好几个小时了,但还不知道怎么做

在我的多处理脚本中:

class ProcessToMonitor(multiprocessing.Process)

def __init__(self):
    multiprocessing.Process.__init__(self)
    self.queue = multiprocessing.Queue()

def run():
    while True:
        # do stuff
        self.queue.put(value)
然后,在我的《龙卷风》剧本中

class MyWebSocket(tornado.websocket.WebSocketHandler):
    connections = set()

    def open(self):
        self.connections.add(self)

    def close(self):
        self.connections.remove(self)

    @classmethod
    def emit(self, message):
        [client.write_message(message) for client in self.connections]

def worker():
    ptm = ProcessToMonitor()
    ptm.start()
    while True:
        message = ptm.queue.get()
        MyWebSocket.emit(message)

if __name__ == '__main__':
    app = tornado.web.Application([
        (r'/', MainHandler), # Not shown
        (r'/websocket', MyWebSocket)
    ])
    app.listen(8888)

    threading.Thread(target=worker)

    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.start()
get不是阻塞函数,它只是等待队列中有一个项目,以防队列为空。我可以从您的代码中看出,queue.get在while循环中非常适合您的用例

我想你可能用错了。您必须将辅助函数设置为协程异步/等待语法:

但是,如果您不想等待某个项目,并且希望立即继续,那么它的替代方案是

这里需要注意的一点是,如果队列为空,queue.get_nowait将引发一个名为的异常。因此,您需要处理该异常

例如:

while True:
    try:
        message = queue.get_nowait()
    except QueueEmpty:
        # wait for some time before
        # next iteration
        # otherwise this loop will
        # keep running for no reason

    MyWebSocket.emit(message)
如您所见,如果队列为空,则必须使用暂停while循环一段时间,以防止其淹没系统


那么,为什么不首先使用queue.get呢?

听起来这只是为了轮询队列。有没有办法设置侦听器/回调?@JonathanWheeler第一个例子根本不是轮询。Tornado将在wait语句处暂停协同路由,并在queue.get返回对象时运行它。这与回调中所做的差不多,但这有更好的语法。
while True:
    try:
        message = queue.get_nowait()
    except QueueEmpty:
        # wait for some time before
        # next iteration
        # otherwise this loop will
        # keep running for no reason

    MyWebSocket.emit(message)