首先,我应该说这可能更多是一个设计问题,而不是代码本身。
我有一个包含一个服务器和多个客户端的网络(用 Twisted 编写,因为我需要这些异步非阻塞特性),这样的服务器-客户端对只是接收-发送消息。
但是,在某些时候,我希望一个客户端在收到特定消息时运行 python 文件。该客户端应该继续监听并与服务器通信,而且,如果需要,我应该能够停止该文件,所以我的第一个想法是为该 python 文件启动一个线程,然后忘记它。
最后它应该是这样的:服务器向 ClientA 发送消息,ClientA 及其 dataReceived 函数解释消息并决定运行该 python 文件(我不知道这需要多长时间,可能包含阻塞调用) ,当该 python 文件完成运行时,应将结果发送给 ClientB。
所以,问题是:
- 为 ClientA 中的 python 文件启动线程是个好主意吗?
- 因为我想将该 python 文件的结果发送给 ClientB,我可以在该 python 文件中有另一个 react 器循环吗?
无论如何,我非常感谢任何类型的建议,因为 python 和 twisted 都不是我的专长,所有这些想法可能都不是最好的。
谢谢!
请您参考如下方法:
初读时,我以为你是在暗示 twisted 不是 python。如果您有这种想法,请记住以下几点:
Twisted is a python framework, I.E. it is python. Specifically it's about getting the most out of a single process/thread/core by allowing the programmer to hand-tune the scheduling/order-of-ops in their own code (which is nearly the opposite of the typical use of threads).
While you can interact with threads in twisted, its quite tricky to do without ruining the efficiency of twisted. (for longer description of threads vs events see SO: https://stackoverflow.com/a/23876498/3334178 )
如果您真的想从扭曲的 Python 中生成新的 Python(即让这项工作在不同的核心上运行),那么我会考虑将其作为一个进程来生成,请参阅 Glyph 在这个 SO 中的回答:https://stackoverflow.com/a/5720492/3334178好的图书馆可以完成这项工作。
进程提供了适当的分离,让你扭曲的应用程序运行时不会出现明显的减速,你应该会发现你所有的启动/停止/暂停/终止需求都将得到满足。
具体回答您的问题:
Would it be starting a thread a good idea for that python file in ClientA?
我会说“不”,这通常不是一个好主意,在您的特定情况下,您应该考虑改用流程。
Can I have another reactor loop inside that python file?
严格来说“不,你不能拥有多个 react 器”——但 twisted 可以同时管理成百上千个独立的任务,所有任务都在同一个 react 器中,将满足你的需要。 IE。在一个 react 器中运行所有不同的异步任务,这就是 twisted 的目的。
顺便说一句,我总是推荐以下关于 twisted 的教程:krondo Twisted Introduction http://krondo.com/?page_id=1327很长,但是如果你把它看完,这样的作品就会变得很清晰。
祝一切顺利!
