如何使用 Twisted 将两个整数相加?
我的程序中有两个整数;我们称它们为“a
”和“b
”。我想将它们加在一起并得到另一个整数作为结果。这些是常规的 Python int
对象。我想知道;如何将它们与 Twisted 添加在一起?某处是否有特殊的 performAsynchronousAddition
函数?我需要延期
吗?反应堆呢?是否涉及反应堆?
I have two integers in my program; let's call them "a
" and "b
". I would like to add them together and get another integer as a result. These are regular Python int
objects. I'm wondering; how do I add them together with Twisted? Is there a special performAsynchronousAddition
function somewhere? Do I need a Deferred
? What about the reactor? Is the reactor involved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,说清楚了。
Twisted 对于CPU 密集型任务没有做任何事情,这是有充分理由的。没有办法通过重新排序子任务来使计算密集型作业运行得更快;您唯一可以做的就是添加更多计算资源;即使这样在 python 中也行不通,因为它的实现很微妙。
Twisted 提供了特殊的语义和事件循环处理,以防程序“陷入困境”,等待其控制之外的某些东西;最常见的是在另一台机器上运行并通过网络连接与扭曲的进程进行通信的进程。由于无论如何您都会等待,Twisted 为您提供了一种同时完成更多事情的机制。也就是说,twisted 为I/O 绑定任务提供并发
tl;dr :twisted 用于网络代码。其他一切都只是普通的Python。
OK, to be clear.
Twisted doesn't do anything about cpu bound tasks and for good reason. there's no way to make a compute bound job go any quicker by reordering subtasks; the only thing you could possibly do is add more compute resources; and even that wouldn't work out in python because of a subtlety of its implementation.
Twisted offers special semantics and event loop handling in case the program would become "stuck" waiting for something outside if its control; most normally a process running on another machine and communicating with your twisted process over a network connection. Since you would be waiting anyways, twisted gives you a mechanism to get more things done in the meantime. That is to say, twisted provides concurrency for I/O Bound tasks
tl;dr: twisted is for network code. Everything else is just normal python.
怎么样:
这应该可行,并且不需要异步完成(它非常快)。
How about this:
That should work, and it doesn't need to be done asynchronously (it's pretty fast).
好问题,Twisted(或 Python)应该有办法至少生成多个核心的“a + b”(在我的 8 核 i7 上)。
不幸的是,Python GIL 阻止了这种情况的发生,这意味着您不仅必须等待 CPU 密集型任务,还必须等待一个核心执行该工作,而其他七个核心则什么都不做。
注意:也许更好的例子是“a() + b()”,甚至“fact(sqrt(a()**b())”等,但重要的事实是上述操作将锁定一个核心,并且GIL 几乎阻止 Python 在该操作期间执行任何其他操作,这可能需要几毫秒......
Good question, and Twisted (or Python) should have a way to at least spawn "a + b" of to several cores (on my 8 core i7).
Unfortunately the Python GIL prevents this from happening, meaning that you will have to wait, not only for the CPU bound task, but for one core doing the job, while the seven others core are doing nothing.
Note: Maybe a better example would be "a() + b()", or even "fact(sqrt(a()**b())" etc. but the important fact is that above operation will lock one core and the GIL pretty much prevents Python for doing anything else during that operation, which could be several ms...