简体   繁体   English

如何将两个整数与Twisted一起添加?

[英]How do I add two integers together with Twisted?

I have two integers in my program; 我的程序中有两个整数; let's call them " a " and " b ". 我们称他们为“ a ”和“ b ”。 I would like to add them together and get another integer as a result. 我想将它们加在一起,结果得到另一个整数。 These are regular Python int objects. 这些是常规的Python int对象。 I'm wondering; 我在想; how do I add them together with Twisted? 如何将它们与Twisted一起添加? Is there a special performAsynchronousAddition function somewhere? 某处有特殊的performAsynchronousAddition功能吗? Do I need a Deferred ? 我需要Deferred吗? What about the reactor? 反应堆怎么样? Is the reactor involved? 是否涉及反应堆?

OK, to be clear. 好的,要清楚。

Twisted doesn't do anything about cpu bound tasks and for good reason. Twisted对cpu绑定任务没有任何意义,并且有充分的理由。 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. 因为它的实现很精细,所以在python中也行不通。

Twisted offers special semantics and event loop handling in case the program would become " stuck " waiting for something outside if its control; Twisted提供了特殊的语义和事件循环处理,以防程序在被控制时变得“ 卡住 ”等待外面的东西; 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. 既然你会等待 ,那么twisted会让你有机会在此期间完成更多工作。 That is to say, twisted provides concurrency for I/O Bound tasks 也就是说,twisted为I / O Bound任务提供并发性

tl;dr: twisted is for network code. tl; dr:twisted用于网络代码。 Everything else is just normal python. 其他一切都只是普通的python。

How about this: 这个怎么样:

c = a + b

That should work, and it doesn't need to be done asynchronously (it's pretty fast). 这应该工作,并且不需要异步完成(它非常快)。

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). 好问题,Twisted(或Python)应该有办法至少产生几个核心的“a + b”(在我的8核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. 不幸的是,Python GIL阻止了这种情况的发生,这意味着你不仅要等待CPU绑定任务,而且还要等待一个核心完成工作,而其他七个核心什么都不做。

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... 注意:也许一个更好的例子是“a()+ b()”,甚至“fact(sqrt(a()** b())”等等,但重要的事实是上面的操作将锁定一个核心和GIL几乎阻止Python在该操作期间做任何其他事情,这可能是几毫秒......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM