[Twisted-Python] Two main loops
I've got a 3D game that I've implemented in Python using an existing game engine. The engine "owns" the main loop, i.e. I call engine.run() and it makes callbacks to my application on every frame (and other game event). Now I'm adding networking, and I'd like to use Twisted. However, Twisted uses the same approach as the game engine -- I call reactor.run() and it makes callbacks to my application. So, how do I integrate the two? My first though is to call reactor.run() in a separate thread, but of course that adds additional complexity in terms of synchronization. I notice the docs mention reactor.iterate(), which appears to be designed for exactly what I'm doing. However, it's not clear how to use it, and the method appears to be deprecated. Any suggestions are appreciated... -- Bernie Roehl Mail: broehl@gmail.com
Am 11.11.2007, 15:03 Uhr, schrieb Bernie Roehl <broehl@gmail.com>:
I've got a 3D game that I've implemented in Python using an existing game engine. The engine "owns" the main loop, i.e. I call engine.run() and it makes callbacks to my application on every frame (and other game event).
Now I'm adding networking, and I'd like to use Twisted. However, Twisted uses the same approach as the game engine -- I call reactor.run() and it makes callbacks to my application.
So, how do I integrate the two?
My first though is to call reactor.run() in a separate thread, but of course that adds additional complexity in terms of synchronization.
I notice the docs mention reactor.iterate(), which appears to be designed for exactly what I'm doing. However, it's not clear how to use it, and the method appears to be deprecated.
Any suggestions are appreciated...
I am using twisted with our home-brewn 3d engine and I do it like this: def DoOneLoopIteration(): engine.RunSingleIteration() reactor.callLater(0, DoOneLoopIteration) reactor.callLater(0, DoOneLoopIteration) reactor.run() There are other possibilities like import twisted.internet.task scheduleUpdate = twisted.internet.task.LoopingCall(DoOneLoopIteration) scheduleUpdate.start(0.01, False) # 100 Hz They all have in common that twisted is driving the main loop and the 3d part of the app only executes the inner part of it's main loop. I tried the opposite way before (3d part of the app driving main loop, twisted being run with iterate()) but this wasn't really usable. -Matthias
Did you find that passing zero as the first parameter to callLater cause it to be called often enough? I really want to make sure the rendering is happening as quickly as possible. So does callLater(0, DoOneLoopIteration) call On Nov 11, 2007 9:20 AM, Nitro <nitro@dr-code.org> wrote:
Am 11.11.2007, 15:03 Uhr, schrieb Bernie Roehl <broehl@gmail.com>:
I've got a 3D game that I've implemented in Python using an existing game engine. The engine "owns" the main loop, i.e. I call engine.run() and it makes callbacks to my application on every frame (and other game event).
Now I'm adding networking, and I'd like to use Twisted. However, Twisted uses the same approach as the game engine -- I call reactor.run() and it makes callbacks to my application.
So, how do I integrate the two?
My first though is to call reactor.run() in a separate thread, but of course that adds additional complexity in terms of synchronization.
I notice the docs mention reactor.iterate(), which appears to be designed for exactly what I'm doing. However, it's not clear how to use it, and the method appears to be deprecated.
Any suggestions are appreciated...
I am using twisted with our home-brewn 3d engine and I do it like this:
def DoOneLoopIteration(): engine.RunSingleIteration() reactor.callLater(0, DoOneLoopIteration)
reactor.callLater(0, DoOneLoopIteration) reactor.run()
There are other possibilities like
import twisted.internet.task scheduleUpdate = twisted.internet.task.LoopingCall(DoOneLoopIteration) scheduleUpdate.start(0.01, False) # 100 Hz
They all have in common that twisted is driving the main loop and the 3d part of the app only executes the inner part of it's main loop. I tried the opposite way before (3d part of the app driving main loop, twisted being run with iterate()) but this wasn't really usable.
-Matthias
_______________________________________________ Twisted-Python mailing list Twisted-Python@twistedmatrix.com http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
-- Bernie Roehl Mail: broehl@gmail.com
On Sun, 11 Nov 2007 09:51:33 -0500, Bernie Roehl <broehl@gmail.com> wrote:
Did you find that passing zero as the first parameter to callLater cause it to be called often enough? I really want to make sure the rendering is happening as quickly as possible.
exarkun@boson:~$ cat howfastdoesitspin.py from twisted.internet import reactor from twisted.internet.task import LoopingCall class Spinner(object): def __init__(self): self.count = 0 def tick(self): self.count += 1 spinner = Spinner() call = LoopingCall(spinner.tick) call.start(0) reactor.callLater(1, reactor.stop) reactor.run() print spinner.count exarkun@boson:~$ python howfastdoesitspin.py 5448 exarkun@boson:~$ Practically speaking, you probably don't need to render more than about 3000 frames per second. ;) Jean-Paul
Am 11.11.2007, 16:44 Uhr, schrieb Jean-Paul Calderone <exarkun@divmod.com>:
On Sun, 11 Nov 2007 09:51:33 -0500, Bernie Roehl <broehl@gmail.com> wrote:
Did you find that passing zero as the first parameter to callLater cause it to be called often enough? I really want to make sure the rendering is happening as quickly as possible.
exarkun@boson:~$ cat howfastdoesitspin.py
from twisted.internet import reactor from twisted.internet.task import LoopingCall
class Spinner(object): def __init__(self): self.count = 0
def tick(self): self.count += 1
spinner = Spinner() call = LoopingCall(spinner.tick) call.start(0) reactor.callLater(1, reactor.stop) reactor.run() print spinner.count exarkun@boson:~$ python howfastdoesitspin.py 5448 exarkun@boson:~$
Practically speaking, you probably don't need to render more than about 3000 frames per second. ;)
HarHar, I get about 13000 on my win machine ;-) -Matthias
Great -- that should work. Thanks everyone for your help! On Nov 11, 2007 10:44 AM, Jean-Paul Calderone <exarkun@divmod.com> wrote:
On Sun, 11 Nov 2007 09:51:33 -0500, Bernie Roehl <broehl@gmail.com> wrote:
Did you find that passing zero as the first parameter to callLater cause it to be called often enough? I really want to make sure the rendering is happening as quickly as possible.
exarkun@boson:~$ cat howfastdoesitspin.py
from twisted.internet import reactor from twisted.internet.task import LoopingCall
class Spinner(object): def __init__(self): self.count = 0
def tick(self): self.count += 1
spinner = Spinner() call = LoopingCall(spinner.tick) call.start(0) reactor.callLater(1, reactor.stop) reactor.run() print spinner.count exarkun@boson:~$ python howfastdoesitspin.py 5448 exarkun@boson:~$
Practically speaking, you probably don't need to render more than about 3000 frames per second. ;)
Jean-Paul
_______________________________________________ Twisted-Python mailing list Twisted-Python@twistedmatrix.com http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
-- Bernie Roehl Mail: broehl@gmail.com
Jean-Paul Calderone wrote:
On Sun, 11 Nov 2007 09:51:33 -0500, Bernie Roehl <broehl@gmail.com> wrote:
Did you find that passing zero as the first parameter to callLater cause it to be called often enough? I really want to make sure the rendering is happening as quickly as possible.
exarkun@boson:~$ cat howfastdoesitspin.py
from twisted.internet import reactor from twisted.internet.task import LoopingCall
class Spinner(object): def __init__(self): self.count = 0
def tick(self): self.count += 1
spinner = Spinner() call = LoopingCall(spinner.tick) call.start(0) reactor.callLater(1, reactor.stop) reactor.run() print spinner.count exarkun@boson:~$ python howfastdoesitspin.py 5448 exarkun@boson:~$
Practically speaking, you probably don't need to render more than about 3000 frames per second. ;)
Jean-Paul
That depends. When I send moderately sized objects over Twisted, this approach causes my frame rate to stop while Twisted is busy, and worse makes my GUI non-interactive. For a game, this is generally unacceptable... I'm not sure of a good/nice way to deal with this. Slicing transmissions into a sequence of smaller chunks seems like a fair pain in the ass, but then again the alternatives are punting to another thread/process. :-/ -Jasper
On 09:06 pm, jasper@peak.org wrote:
That depends. When I send moderately sized objects over Twisted, this approach causes my frame rate to stop while Twisted is busy, and worse makes my GUI non-interactive. For a game, this is generally unacceptable...
You can't send "objects" over "Twisted". Are you talking about a particular protocol in Twisted? Serializing large objects through PB might take a long time. In that case, it's not "Twisted" that is busy, but your program which is busy serializing that object.
I'm not sure of a good/nice way to deal with this. Slicing transmissions into a sequence of smaller chunks seems like a fair pain in the ass, but then again the alternatives are punting to another thread/process. :-/
Actually, punting to another thread or process is still going to slow down your rendering, but in a much less deterministic way. The OS scheduler is going to be interrupting the rendering rather than the long-running serialization function. Breaking down the serialization work into smaller chunks will allow you to better control what's going on. Sending the work of serializing a large object to another process won't work anyway: how are you going to get that large object to the other process to serialize in the first place, without serializing it? Sending it to another thread probably won't work either, since if the object is large it is likely shared (and therefore will involve locking large portions of the data structure for long periods of time) and Python's GIL will introduce deleterious effects for your framerate anyway. Fundamentally what you are doing here is optimizing your program. Your serialization is slow and it needs to be faster so that it does not impact your framerate. This is a difficult problem, one which is made worse by the fact that Python does not have a particularly fast runtime. There's no quick answer: you don't need to restructure your main loop, you need to think about what your program is spending its time doing.
First off, thanks for the reply! My responses/questions are inline below. -Jasper glyph@divmod.com wrote:
On 09:06 pm, jasper@peak.org wrote:
That depends. When I send moderately sized objects over Twisted, this approach causes my frame rate to stop while Twisted is busy, and worse makes my GUI non-interactive. For a game, this is generally unacceptable... You can't send "objects" over "Twisted".
Sure, not per se. However, you can essentially send copies of objects through PB, provided both sides of the wire have the same class definition.
Are you talking about a particular protocol in Twisted? Serializing large objects through PB might take a long time. In that case, it's not "Twisted" that is busy, but your program which is busy serializing that object.
It comes in the twisted installation package, in the module "twisted.spread.pb" ;-) Anyway, the delay comes in a call to (a) perspective.callRemote(). I understand that this isn't a reactor scheduled action, but nonetheless I don't have any direct control over how things are jellied without hacking Twisted.
I'm not sure of a good/nice way to deal with this. Slicing transmissions into a sequence of smaller chunks seems like a fair pain in the ass, but then again the alternatives are punting to another thread/process. :-/
Actually, punting to another thread or process is still going to slow down your rendering, but in a much less deterministic way. The OS scheduler is going to be interrupting the rendering rather than the long-running serialization function. Breaking down the serialization work into smaller chunks will allow you to better control what's going on.
Sending the work of serializing a large object to another process won't work anyway: how are you going to get that large object to the other process to serialize in the first place, without serializing it? Sending it to another thread probably won't work either, since if the object is large it is likely shared (and therefore will involve locking large portions of the data structure for long periods of time) and Python's GIL will introduce deleterious effects for your framerate anyway.
In hindsight I see a separate process won't work (duh!) However, I was thinking a thread might work, since the data I'm sending (players get a filtered view of the game's true state) isn't used by anything else, and the data isn't /that/ large. ;-) Am I missing something low level here? Would this end up locking bits other than those being serialized? I suppose it's a bit moot, as I'm reluctant to fiddle with threading.
Fundamentally what you are doing here is optimizing your program. Your serialization is slow and it needs to be faster so that it does not impact your framerate. This is a difficult problem, one which is made worse by the fact that Python does not have a particularly fast runtime. There's no quick answer: you don't need to restructure your main loop, you need to think about what your program is spending its time doing.
Optimizing my program (e.g. by sending a bunch of smaller data chunks) feels like the wrong way to go... Wouldn't it make more sense to hack PB's callRemote() to do this in a more general manner? I'm thinking somewhere around jelly._Jellier.jelly()'s recursive calls to itself; perhaps using generators, although I'm fuzzy on the implications of recursion + generators... Either way it's definitely optimization, so not exactly a pressing issue for me to resolve until the end. -Jasper
On 06:23 pm, jasper@peak.org wrote:
glyph@divmod.com wrote:
On 09:06 pm, jasper@peak.org wrote:
You can't send "objects" over "Twisted".
Sure, not per se.
It comes in the twisted installation package, in the module "twisted.spread.pb" ;-)
There are a number of other ways to communicate with other programs using Twisted, some of which involve "sending objects" through other protocols. Obviously PB is a part of Twisted :).
In hindsight I see a separate process won't work (duh!) However, I was thinking a thread might work, since the data I'm sending (players get a filtered view of the game's true state) isn't used by anything else, and the data isn't /that/ large. ;-) Am I missing something low level here? Would this end up locking bits other than those being serialized?
I suppose it's a bit moot, as I'm reluctant to fiddle with threading.
If you've got a large object, let's say the state of the game world, and you need to lock it for use within a thread, it is likely that other things in your program will want to access it before long. You can only have so many "large" objects in a program, after all, and they tend to be shared. The one you referred to, "the game's true state", is obviously going to be accessed by a lot of code unless you have a very strange game indeed.
Optimizing my program (e.g. by sending a bunch of smaller data chunks) feels like the wrong way to go... Wouldn't it make more sense to hack PB's callRemote() to do this in a more general manner? I'm thinking somewhere around jelly._Jellier.jelly()'s recursive calls to itself; perhaps using generators, although I'm fuzzy on the implications of recursion + generators...
callRemote *can't* do this in a general manner and remain compatible with PB's existing semantics. It would be extraordinarily difficult to come up with semantics that would make sense for this. Consider: bob = Mob(hitPoints=3) jethro = Player() jethro.callRemote("enterSensoryRange", bob) bob.hitPoints += 1 How many hit points does Jethro think Bob has? Probably 3, but if PB might be breaking up serialization work into separate reactor turns for you behind your back, then maybe 4. Given that there's no way to know, you don't know whether you have to send Jethro an update to bob's hit points or not. If you can figure out how to answer this question in a way that makes sense (i.e. never uses the word "maybe") then you might be able to implement something very cool and useful. I certainly can't think of a way to do it, though. Good luck!
On Mon, 12 Nov 2007 21:17:47 -0000, glyph@divmod.com wrote:
On 06:23 pm, jasper@peak.org wrote:
glyph@divmod.com wrote:
[snip]
callRemote *can't* do this in a general manner and remain compatible with PB's existing semantics. It would be extraordinarily difficult to come up with semantics that would make sense for this. Consider:
bob = Mob(hitPoints=3) jethro = Player() jethro.callRemote("enterSensoryRange", bob) bob.hitPoints += 1
How many hit points does Jethro think Bob has? Probably 3, but if PB might be breaking up serialization work into separate reactor turns for you behind your back, then maybe 4. Given that there's no way to know, you don't know whether you have to send Jethro an update to bob's hit points or not.
If you can figure out how to answer this question in a way that makes sense (i.e. never uses the word "maybe") then you might be able to implement something very cool and useful. I certainly can't think of a way to do it, though. Good luck!
It's always possible to provide new behavior - all you have to do is provide a new API. For example, RemoteReference.callRemoteAsyncly(). Jean-Paul
Jean-Paul Calderone wrote:
On Mon, 12 Nov 2007 21:17:47 -0000, glyph@divmod.com wrote:
If you can figure out how to answer this question in a way that makes sense (i.e. never uses the word "maybe") then you might be able to implement something very cool and useful. I certainly can't think of a way to do it, though. Good luck!
It's always possible to provide new behavior - all you have to do is provide a new API. For example, RemoteReference.callRemoteAsyncly().
That's basically what I had in mind. I wouldn't want to change the behavior of callRemote() at all, as that could hit existing programs by surprise. Well, assuming I manage to get you guys to include whatever hack I come up with, and it doesn't just live on my SVN'd version. ;-) -Jasper
glyph@divmod.com wrote:
On 06:23 pm, jasper@peak.org wrote:
glyph@divmod.com wrote In hindsight I see a separate process won't work (duh!) However, I was thinking a thread might work, since the data I'm sending (players get a filtered view of the game's true state) isn't used by anything else, and the data isn't /that/ large. ;-) Am I missing something low level here? Would this end up locking bits other than those being serialized?
I suppose it's a bit moot, as I'm reluctant to fiddle with threading.
If you've got a large object, let's say the state of the game world, and you need to lock it for use within a thread, it is likely that other things in your program will want to access it before long. You can only have so many "large" objects in a program, after all, and they tend to be shared. The one you referred to, "the game's true state", is obviously going to be accessed by a lot of code unless you have a very strange game indeed. I don't send the players the "True State", I first calculate a trimmed and altered copy of it, according to what they can perceive. I then send this, which in practice isn't used by anything else on the server.
Optimizing my program (e.g. by sending a bunch of smaller data chunks) feels like the wrong way to go... Wouldn't it make more sense to hack PB's callRemote() to do this in a more general manner? I'm thinking somewhere around jelly._Jellier.jelly()'s recursive calls to itself; perhaps using generators, although I'm fuzzy on the implications of recursion + generators...
callRemote *can't* do this in a general manner and remain compatible with PB's existing semantics. It would be extraordinarily difficult to come up with semantics that would make sense for this. Consider:
bob = Mob(hitPoints=3) jethro = Player() jethro.callRemote("enterSensoryRange", bob) bob.hitPoints += 1
How many hit points does Jethro think Bob has? Probably 3, but if PB might be breaking up serialization work into separate reactor turns for you behind your back, then maybe 4. Given that there's no way to know, you don't know whether you have to send Jethro an update to bob's hit points or not.
If you can figure out how to answer this question in a way that makes sense (i.e. never uses the word "maybe") then you might be able to implement something very cool and useful. I certainly can't think of a way to do it, though. Good luck!
For my game, that's actually pretty straight forward, as I don't allow such complex situations. I allow 3 things though PB: 1) Ask for status 2) Request current state 3) send actions for the current turn Clients never actually /do/ anything (eg "enterSensoryRange), but instead schedule actions for the game server to carry out on their behalf at a later time (simultaneously with other players' actions). The only time a client get a large chunk of data is when it's asked for it, and clients know enough to wait for a response. It's possible for the client to send actions based on an old turn right before a new turn is processed, but these are simply tossed out with a warning that they're out of date, and the client should update it's state. Reworking the above example, Jethro would always see that Bob has 3 hitpoints on turn X, and 4 hitpoints on turn X+1. Jethro's "enterSensoryRange" attempt would be made for a specific turn, say X. If it arrives before turn X+1 is calculated, he gets his result on turn X+1. If it arrives late, well then Jethro was too slow. For a more general case perhaps it's more complicated... -Jasper
Actually, punting to another thread or process is still going to slow down your rendering, but in a much less deterministic way. The OS scheduler is going to be interrupting the rendering rather than the long-running serialization function. Breaking down the serialization work into smaller chunks will allow you to better control what's going on.
Holy crap! I just grew an extra brain cell! It has tingly sensation like selson blue. So let me offer some empirical evidence of this phenomenon which I was not quite understanding until reading your comment - of course, it makes complete sense now. I've been working on a cheesey game in my spare time called Twisted Wars (yes, the Twisted), and just to amuse myself I decided to run the reactor normally rather than threaded select and model the runtime loop as a cooperative iterator - the idea being that eventually the runtime loop could be many cooiterators, to allow for an actor-based system. To my surprise, after changing the core runtime to a cooiterator, my frame rate improved (albeit only about +5 - but this might be more noticeable if I had a decent frame rate to start with). I explained to a friend who's also working on the game and they refused to believe me! Ha! -Drew -- \\\\\/\"/\\\\\\\\\\\ \\\\/ // //\/\\\\\\\ \\\/ \\// /\ \/\\\\ \\/ /\/ / /\/ /\ \\\ \/ / /\/ /\ /\\\ \\ / /\\\ /\\\ \\\\\/\ \/\\\\\/\\\\\/\\\\\\ d.p.s
On 14 Nov, 07:08 pm, drew.smathers@gmail.com wrote:
Actually, punting to another thread or process is still going to slow down your rendering, but in a much less deterministic way. The OS scheduler is going to be interrupting the rendering rather than the long-running serialization function. Breaking down the serialization work into smaller chunks will allow you to better control what's going on.
Holy crap! I just grew an extra brain cell! It has tingly sensation like selson blue.
Nice to hear that we're helping to increase the transistor density of the universe.
So let me offer some empirical evidence of this phenomenon which I was not quite understanding until reading your comment - of course, it makes complete sense now. I've been working on a cheesey game in my spare time called Twisted Wars (yes, the Twisted), and just to amuse myself I decided to run the reactor normally rather than threaded select and model the runtime loop as a cooperative iterator - the idea being that eventually the runtime loop could be many cooiterators, to allow for an actor-based system.
I've seen Twisted Wars. It's flattering, but I hope it's going to evolve from beyond its, ahem, "humble" beginnings into something more interesting :). Nice to unveil the mystery of its author, though ...
To my surprise, after changing the core runtime to a cooiterator, my frame rate improved (albeit only about +5 - but this might be more noticeable if I had a decent frame rate to start with). I explained to a friend who's also working on the game and they refused to believe me! Ha!
Although I'm glad you've gained some insight into the exciting world of improving performance (or not) with parallelism, I wouldn't read too much into this. threadedselectreactor is a particularly poorly-tested piece of code and it might have performance bugaboos of its own that have nothing to do with concurrency. Also, as I said, I've tried Twisted Wars; one of the things I noticed about it is that the framerate seems to degrade slowly over time until the game becomes sluggish and unplayable. It seems like you're leaking computation somewhere. So you've got a lot of factors to consider when measuring your overall framerate.
Although I'm glad you've gained some insight into the exciting world of improving performance (or not) with parallelism, I wouldn't read too much into this. threadedselectreactor is a particularly poorly-tested piece of code and it might have performance bugaboos of its own that have nothing to do with concurrency. Also, as I said, I've tried Twisted Wars; one of the things I noticed about it is that the framerate seems to degrade slowly over time until the game becomes sluggish and unplayable. It seems like you're leaking computation somewhere. So you've got a lot of factors to consider when measuring your overall framerate.
Yes, it leaks like a dam in Holland. That was a bug that cropped up at the end of the competition. But that's become the new goal of the game - get as money as money as possible before your memory is full and you die. The minor performance boost was observable at the start of the game before the scenes are flooded with unclaimed TCP rays. If there is a next game, I'll probably start from scratch and take more careful steps to prove the scene artifact management is robust before diving into anything more complex. Thanks for your input. -- \\\\\/\"/\\\\\\\\\\\ \\\\/ // //\/\\\\\\\ \\\/ \\// /\ \/\\\\ \\/ /\/ / /\/ /\ \\\ \/ / /\/ /\ /\\\ \\ / /\\\ /\\\ \\\\\/\ \/\\\\\/\\\\\/\\\\\\ d.p.s
On Sunday 11 November 2007, Jasper wrote:
Jean-Paul Calderone wrote:
Practically speaking, you probably don't need to render more than about 3000 frames per second. ;)
Jean-Paul
That depends. When I send moderately sized objects over Twisted, this approach causes my frame rate to stop while Twisted is busy, and worse makes my GUI non-interactive. For a game, this is generally unacceptable...
Why would that happen? Twisted never blocks; if it has to wait for something (such as a transmission buffer becoming ready to accept more data), it will register a callback and the reactor will continue (and call your rendering code). Bye, Maarten
Maarten ter Huurne wrote:
On Sunday 11 November 2007, Jasper wrote:
Jean-Paul Calderone wrote:
Practically speaking, you probably don't need to render more than about 3000 frames per second. ;)
Jean-Paul
That depends. When I send moderately sized objects over Twisted, this approach causes my frame rate to stop while Twisted is busy, and worse makes my GUI non-interactive. For a game, this is generally unacceptable...
Why would that happen?
Twisted never blocks; if it has to wait for something (such as a transmission buffer becoming ready to accept more data), it will register a callback and the reactor will continue (and call your rendering code).
Bye, Maarten
Maybe I'm misunderstanding what's going on underneath, but Twisted sure seems to block while I send one large chunk of data. -Jasper
On Mon, 12 Nov 2007 08:58:55 -0800, Jasper <jasper@peak.org> wrote:
Maarten ter Huurne wrote:
On Sunday 11 November 2007, Jasper wrote:
Jean-Paul Calderone wrote:
Practically speaking, you probably don't need to render more than about 3000 frames per second. ;)
Jean-Paul
That depends. When I send moderately sized objects over Twisted, this approach causes my frame rate to stop while Twisted is busy, and worse makes my GUI non-interactive. For a game, this is generally unacceptable...
Why would that happen?
Twisted never blocks; if it has to wait for something (such as a transmission buffer becoming ready to accept more data), it will register a callback and the reactor will continue (and call your rendering code).
Bye, Maarten
Maybe I'm misunderstanding what's going on underneath, but Twisted sure seems to block while I send one large chunk of data.
There are a lot of different pieces in any non-trivial program. There are also at least a couple different meanings for the word "block". The network code at the very bottom of Twisted won't ever wait for a network event to happen before continuing execution. That's what Maarten ter Huurne was pointing out. Some parts of Twisted (for example, the serializers for PB) might spend a long time using the CPU in order to provide the functionality they are supposed to provide. The main difference between these two cases is that in the former, you are subject to arbitrary delays by other parties whereas in the latter case, the delays are in response to actions your application has explicitly taken. The latter case can be solved by asking functions to do less work at a time, as has been suggested a couple times in this thread. Since the former case never happens in Twisted, there's no need to fix it. :) Jean-Paul
Jean-Paul Calderone wrote:
On Mon, 12 Nov 2007 08:58:55 -0800, Jasper <jasper@peak.org> wrote:
Maarten ter Huurne wrote:
Why would that happen?
Twisted never blocks; if it has to wait for something (such as a transmission buffer becoming ready to accept more data), it will register a callback and the reactor will continue (and call your rendering code).
Bye, Maarten
Maybe I'm misunderstanding what's going on underneath, but Twisted sure seems to block while I send one large chunk of data.
There are a lot of different pieces in any non-trivial program. There are also at least a couple different meanings for the word "block". [further elaboration snipped]
I think the confusion here is stemming from us attaching different meanings to "Twisted". I've been meaning the entire package, i.e. the modules I got when I installed Twisted. You (Glyph, Maarten, etc.) seem to mean only the lower level inner bits, like reactor. I'd actually understood this when I sent the above, and I apologize for the snarky reply. ;-) To get to the point, I actually do feel that the fault lies with Twisted, or more specifically PB. Code using PB wants to be as unaware of the details of network transmission as possible. It certainly doesn't want to slice things into a bazillion chunks for individual transmission, and then puzzle them back together on the other end. IMHO it makes more sense for PB to understand it shouldn't block, and to chunk and schedule its serialization (and unserialization) in the same manner as the TCP packets sent underneath. I'm guessing this would make for cleaner separation, and more general usefulness. Also, let me clarify that I'm not suggesting that someone else do this, nor bitching and moaning about what I'm getting out of a free project; it's something I intend to do myself as I have time. -Jasper
Am 12.11.2007, 19:47 Uhr, schrieb Jasper <jasper@peak.org>:
To get to the point, I actually do feel that the fault lies with Twisted, or more specifically PB. Code using PB wants to be as unaware of the details of network transmission as possible. It certainly doesn't want to slice things into a bazillion chunks for individual transmission, and then puzzle them back together on the other end.
IMHO it makes more sense for PB to understand it shouldn't block, and to chunk and schedule its serialization (and unserialization) in the same manner as the TCP packets sent underneath. I'm guessing this would make for cleaner separation, and more general usefulness.
I think this is a) not possible and b) not desirable. It's not possible because pb sends a single large chunk of data over tcp. The OS is responsible to break everything down into individual tcp packets and puzzle them together at the other end. The whole packet thing is not visible to pb. So if you want pb to split your data, then do splitted callRemotes. It's not desirable because you don't want your program to be stalled at uncontrollable times when the OS decides to send 20 tcp packets at once. You want to spread the load as evenly as possible and you'll have to do this manually. Which kind of game are you working on and how many connections/bandwidth does it have? I haven't encountered the problems you mention in my project. -Matthias
On Mon, 12 Nov 2007 20:08:29 +0100, Nitro <nitro@dr-code.org> wrote:
Am 12.11.2007, 19:47 Uhr, schrieb Jasper <jasper@peak.org>:
To get to the point, I actually do feel that the fault lies with Twisted, or more specifically PB. Code using PB wants to be as unaware of the details of network transmission as possible. It certainly doesn't want to slice things into a bazillion chunks for individual transmission, and then puzzle them back together on the other end.
IMHO it makes more sense for PB to understand it shouldn't block, and to chunk and schedule its serialization (and unserialization) in the same manner as the TCP packets sent underneath. I'm guessing this would make for cleaner separation, and more general usefulness.
I think this is a) not possible and b) not desirable.
I think it's possible. It may even be desirable, although whether it is worth the cost of implementing or not is a question worth considering.
It's not possible because pb sends a single large chunk of data over tcp.
It doesn't have to be implemented this way. However, this isn't particularly relevant. ITCPTransport.write takes approximately the same amount of time to execute and return whether you pass it a string which is one byte long or one million bytes long.
The OS is responsible to break everything down into individual tcp packets and puzzle them together at the other end. The whole packet thing is not visible to pb.
True, but the actual performance bottleneck here is in PB's conversion of Python objects to strings, which is done by code entirely within Twisted.
So if you want pb to split your data, then do splitted callRemotes. It's not desirable because you don't want your program to be stalled at uncontrollable times when the OS decides to send 20 tcp packets at once.
Your program won't ever stall because of this.
You want to spread the load as evenly as possible and you'll have to do this manually.
PB's serializer could try very hard to avoid running for a long period of time without giving control back to the reactor. Of course, someone would have to implement this. Whether or not that is worthwhile to implement, instead of doing what Glyph suggested (manually breaking up the work into smaller pieces) is a separate question. Jean-Paul
Am 12.11.2007, 21:15 Uhr, schrieb Jean-Paul Calderone <exarkun@divmod.com>:
The OS is responsible to break everything down into individual tcp packets and puzzle them together at the other end. The whole packet thing is not visible to pb.
True, but the actual performance bottleneck here is in PB's conversion of Python objects to strings, which is done by code entirely within Twisted.
Yes.
So if you want pb to split your data, then do splitted callRemotes. It's not desirable because you don't want your program to be stalled at uncontrollable times when the OS decides to send 20 tcp packets at once.
Your program won't ever stall because of this.
If you do it as Jesper suggested and serialize when packets are about to be send then it will stall when you try to send (=serialize) lots of packets at once.
You want to spread the load as evenly as possible and you'll have to do this manually.
PB's serializer could try very hard to avoid running for a long period of time without giving control back to the reactor. Of course, someone would have to implement this. Whether or not that is worthwhile to implement, instead of doing what Glyph suggested (manually breaking up the work into smaller pieces) is a separate question.
Of course you can do it. But does it make sense? If you ask pb to do lots of work then you can't be surprised it takes long. If I ask pb to serialize things I want it to do it *now*. If pb starts distributing work over time itself then I will end up with lags which are bad in my situation. I'd like to hear about the actual situation where twisted is stalling because of serialization. As said before I am using pb and a pb-like thing which also uses banana for serialization (= even more overhead to generate messages and spread them over multiple udp packets). I am serializing lots of data and it works like a charm. After all if you have so much data to serialize then you are very likely to do something with the data on the sending and receiving end. And this processing is much more likely to be a performance bottleneck than twisted serialization. I guess we can discuss a lot about how pb *could* work. We should keep in mind real world situations though which tend to shift priorities a lot. -Matthias
Jean-Paul Calderone wrote:
On Mon, 12 Nov 2007 20:08:29 +0100, Nitro <nitro@dr-code.org> wrote:
Am 12.11.2007, 19:47 Uhr, schrieb Jasper <jasper@peak.org>:
To get to the point, I actually do feel that the fault lies with Twisted, or more specifically PB. Code using PB wants to be as unaware of the details of network transmission as possible. It certainly doesn't want to slice things into a bazillion chunks for individual transmission, and then puzzle them back together on the other end.
IMHO it makes more sense for PB to understand it shouldn't block, and to chunk and schedule its serialization (and unserialization) in the same manner as the TCP packets sent underneath. I'm guessing this would make for cleaner separation, and more general usefulness.
I think this is a) not possible and b) not desirable.
I think it's possible. It may even be desirable, although whether it is worth the cost of implementing or not is a question worth considering.
[snip]
PB's serializer could try very hard to avoid running for a long period of time without giving control back to the reactor. Of course, someone would have to implement this. Whether or not that is worthwhile to implement, instead of doing what Glyph suggested (manually breaking up the work into smaller pieces) is a separate question.
I'm not sure it's worth the cost either, but I'm also not splitting up the data into chunks is easier. Looking through jelly.py, I find the places I'd want to split data align pretty closely with the chunking already done during jellying; why duplicate this work? That said, I'm not precisely sure how to keep track of progress between time slices, although I nebulously intuit it could be done via nested generators. I'm sure I don't fully understand the implications of this, but I've been looking for a practical reason to fiddle with generators for a while anyway. ;-) -Jasper
Nitro wrote:
Am 12.11.2007, 19:47 Uhr, schrieb Jasper <jasper@peak.org>:
To get to the point, I actually do feel that the fault lies with Twisted, or more specifically PB. Code using PB wants to be as unaware of the details of network transmission as possible. It certainly doesn't want to slice things into a bazillion chunks for individual transmission, and then puzzle them back together on the other end.
IMHO it makes more sense for PB to understand it shouldn't block, and to chunk and schedule its serialization (and unserialization) in the same manner as the TCP packets sent underneath. I'm guessing this would make for cleaner separation, and more general usefulness.
I think this is a) not possible and b) not desirable. It's not possible because pb sends a single large chunk of data over tcp. The OS is responsible to break everything down into individual tcp packets and puzzle them together at the other end. The whole packet thing is not visible to pb. So if you want pb to split your data, then do splitted callRemotes. I'm not thinking of splitting up packets. I'm merely thinking of splitting up serialization, and not splitting the data.
It's not desirable because you don't want your program to be stalled at uncontrollable times when the OS decides to send 20 tcp packets at once. You want to spread the load as evenly as possible and you'll have to do this manually. Which kind of game are you working on and how many connections/bandwidth does it have? I haven't encountered the problems you mention in my project.
Turn based strategy. Here's the (rather out of date) website if your curious: http://brass-golem.com/ -Jasper
In a game you usually never send/receive huge objects. For various reasons you always try to reduce your bandwidth as much as possible. A low bandwidth implies a rather low number of objects and data. That being said I am using pb for transferring state changes which should be guarenteed to arrive (for example a command to load a new game world) and using a custom pb-like method based on udp and which uses messaging/packaging for things which do not have to be transmitted on a guarenteed basis. An example for the latter is updates of the position of world objects for instance. If a udp packet is lost, I don't really care because a new one will be send very soon anyways. I am able to render (client) / simulate (server) with more than 200 fps this way. So while python might be slow compared to C++ this proves that it's actually possible to write python code which performs fast enough. It also proves that it's more important to optimize your algorithms and not your code. In the case of a game this means to think about ways to reduce the data that needs to be transmitted instead of making the serialization/network code faster. -Matthias Am 11.11.2007, 22:06 Uhr, schrieb Jasper <jasper@peak.org>:
That depends. When I send moderately sized objects over Twisted, this approach causes my frame rate to stop while Twisted is busy, and worse makes my GUI non-interactive. For a game, this is generally unacceptable...
I'm not sure of a good/nice way to deal with this. Slicing transmissions into a sequence of smaller chunks seems like a fair pain in the ass, but then again the alternatives are punting to another thread/process. :-/
-Jasper
In a game you usually never send/receive huge objects. For various reasons you always try to reduce your bandwidth as much as possible. A low bandwidth implies a rather low number of objects and data. Actually, in my (and most) turn based strategy games, it's normal to send lots of data, every turn. Not all games are realtime, with data
Nitro wrote: that fits easily into small packets. -Jasper
On Nov 12, 2007 11:56 AM, Jasper <jasper@peak.org> wrote:
In a game you usually never send/receive huge objects. For various reasons you always try to reduce your bandwidth as much as possible. A low bandwidth implies a rather low number of objects and data. Actually, in my (and most) turn based strategy games, it's normal to send lots of data, every turn. Not all games are realtime, with data
Nitro wrote: that fits easily into small packets.
-Jasper <http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python>
For this specific use case, I would expect using a producer/consumer: http://twistedmatrix.com/projects/core/documentation/howto/producers.html However, it still seems unlikely that you'd need to transmit that much data even in a turn-based system. How many bytes are we talking about? -- \\\\\/\"/\\\\\\\\\\\ \\\\/ // //\/\\\\\\\ \\\/ \\// /\ \/\\\\ \\/ /\/ / /\/ /\ \\\ \/ / /\/ /\ /\\\ \\ / /\\\ /\\\ \\\\\/\ \/\\\\\/\\\\\/\\\\\\ d.p.s
On Sun, 2007-11-11 at 15:20 +0100, Nitro wrote:
Now I'm adding networking, and I'd like to use Twisted. However, Twisted uses the same approach as the game engine -- I call reactor.run() and it makes callbacks to my application.
So, how do I integrate the two?
I am using twisted with our home-brewn 3d engine and I do it like this:
def DoOneLoopIteration(): engine.RunSingleIteration() reactor.callLater(0, DoOneLoopIteration)
reactor.callLater(0, DoOneLoopIteration) reactor.run()
Or, if your game event loop supports registering sockets, you could build your own reactor; that's e.g. how twisted.internet.glib2reactor works, using glib's event loop and socket notification mechanism.
participants (8)
-
Bernie Roehl -
Drew Smathers -
glyph@divmod.com -
Itamar Shtull-Trauring -
Jasper -
Jean-Paul Calderone -
Maarten ter Huurne -
Nitro