From: Jan Dvorak Date: 2008-05-28T22:19:36+09:00 Subject: Re: Writing event hooks called from C extensions On Tuesday 27 May 2008 21:44:37 Matthijs Langenberg wrote: > Just for educational purposes, I'm trying to write a Ruby-C extension > that allows me to hook into Carbon's event handler. So I can handle > mouse clicks in Ruby. > Mouse clicks (like all events) happen asynchronously, meaning that > something needs to be running inside a seperate thread, but I find it > hard to grasp how this all works out. > > I've already figured out the following code: http://pastie.org/204180. > This allows me to include the 'MouseEvents' module somewhere and call > 'hook'. This works, and prints 'click' to my console, but it blocks > ruby. > > Would it be possible to start a seperate Thread from inside the C > extension, which calls into ruby (or executes a block) asynchronously? Not really, the problem is, ruby isn't exactly multi-threading atm (somebody correct me if i'm wrong), 1.8 doesn't use OS threads at all and concurrency is done by timeslicing, 1.9 does use native threads but only one thread, but VM is shared so only one thread can run at a time. I don't know Carbon but as i see it you have two options - first, if you're happy with using just the hooker functions, you can simply call the ruby function from inside your myeventhandler(s), of course you can't run any other code parallel to event handling (unless you start another ruby interpreter and synchronize somehow). Second, you can abandon RunApplicationEventLoop and use manual event polling (i'm sure Carbon has one), then you can write the event handling as C function that takes block and iterates it - it would then be used from ruby as: ... register_hooks() ... loop_events() do # do some stuff end # here the C function polls next event and if any, calls the appropriate ruby hooked functions, Jan