问题
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?
回答1:
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.
回答2:
How about this:
c = a + b
That should work, and it doesn't need to be done asynchronously (it's pretty fast).
回答3:
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...
来源:https://stackoverflow.com/questions/7313761/how-do-i-add-two-integers-together-with-twisted