Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.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 异步IO启动\u服务器超时问题_Python_Python 3.x_Tcp_Python Asyncio - Fatal编程技术网

Python 异步IO启动\u服务器超时问题

Python 异步IO启动\u服务器超时问题,python,python-3.x,tcp,python-asyncio,Python,Python 3.x,Tcp,Python Asyncio,我有一个用Python实现的TCP服务器,使用asyncio的create\u server 我使用连接处理程序\u cb调用协同程序启动\u服务器 现在我的问题是:假设我的连接\u处理程序\u cb看起来像什么 像这样: def connection_handler_cb(reader, writer): while True: yield from reader.read() --do some computation--

我有一个用Python实现的TCP服务器,使用asyncio的
create\u server

我使用
连接处理程序\u cb
调用协同程序
启动\u服务器
现在我的问题是:假设我的
连接\u处理程序\u cb
看起来像什么
像这样:

   def connection_handler_cb(reader, writer):
       while True:  
           yield from reader.read()
           --do some computation--  
我知道只有来自coroutines的
yield被“并发”运行(我知道它不是真正并发的),所有的--“做一些计算--”部分都被顺序调用,并且阻止了其他所有部分在循环中运行


假设我们正在讨论一个TCP服务器,其中有多个客户端试图发送数据。这种情况是否会导致另一端(客户端)的发送超时

如果您的客户端正在等待服务器的响应,并且该响应在计算完成之前不会发送,那么如果计算花费足够长的时间,客户端可能最终会超时。不过,更可能的情况是,客户端将一直挂起,直到计算完成并且事件循环被解除阻塞

在任何情况下,如果您担心超时或挂起,请使用在后台进程(最好是这样)或线程(可能不是一个好选择,因为您正在执行CPU限制的计算)中运行计算,而不阻塞事件循环:

  import asyncio
  import multiprocessing
  from concurrent.futures import ProcessPoolExecutor

  def comp_func(arg1, arg2):
       # Do computation here
       return output

  def connection_handler_cb(reader, writer):
       while True:  
           yield from reader.read()
           # Do computation in a background process
           # This won't block the event loop.
           output = yield from loop.run_in_executor(None, comp_func, arg1, arg2) #
  if __name__ == "__main__":
      executor = 
      loop = asyncio.get_event_loop()
      loop.set_default_executor(
           ProcessPoolExecutor(multiprocessing.cpu_count()))
      asyncio.async(asyncio.start_server(connect_handler_cb, ...))
      loop.run_forever()