Worker threads in Ruby
Asked Answered
S

3

6

I am writing a simple memory game using ruby + qt (trying to get away from c++ for while...)
In order to allow a X second timeout to view two open pieces, I need either timers or do the work in a background thread.

What is the simplest way of implementing this without reinventing the wheel?
Ruby threads? Qt threads? Qt timers?

Spoofery answered 24/11, 2008 at 7:58 Comment(0)
V
4

I dont know if it is the best solution but:

block=Proc.new{ Thread.pass }
timer=Qt::Timer.new(window)
invoke=Qt::BlockInvocation.new(timer, block, "invoke()")
Qt::Object.connect(timer, SIGNAL("timeout()"), invoke, SLOT("invoke()"))
timer.start(1)

Makes ruby threads work! Adjust start(x) for your needs.

Vaporing answered 17/2, 2009 at 18:25 Comment(1)
This is going to come in very handy for me ... +1Claudioclaudius
M
2

The decision to choose QT threads/timers or Ruby ones is probably a personal one, but you should remember that Ruby threads are green. This means that they are implemented by the Ruby interpreter and cannot scale across multiple processor cores. Though, for a simple memory game with a timer I'm guessing you probably don't need to worry about that.

Although somewhat unrelated, Midiator, a Ruby interface to MIDI devices uses Ruby threads to implement a timer.

Also, have a look at Leslie Viljoen's article, he says that Ruby's threads lock up when QT form widgets are waiting for input. He also provides some sample code to implement QT timers (which look quite easy and appropiate for what you are doing).

Mondrian answered 24/11, 2008 at 10:58 Comment(0)
S
0

Thanks.

Solved it using QTimer::singleShot. Sufficient - in my case, fires a one time timer every time two tiles are displayed.

Spoofery answered 25/11, 2008 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.