Worker threads in Ruby - ruby

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?

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.

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).

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

Related

How to specify thread priority?

I need to run multiple threads on an embedded-linux target.
One of the threads requires a lot of resources so I need it to run in background at a low priority.
There will be times when the higher priority threads will have nothing to do. A typical vala Thread.create looks like this:
Thread.create<void*> (pProcessor->run, true);
Is there a way to specify the thread priority?
You can't use the threading stuff in GLib, you would have to use pthreads directly. There is some information on how to do that in C here. You would also need to create Vala bindings for the relevant functions since nobody has done so yet (it's pretty easy... if you understand how Vala maps to C it would only take a couple minutes).
If I were you I would look into using a priority queue instead. If you don't feel like writing your own bump should already have everything you need (specifically, Semaphore and/or TaskQueue), or AsyncPriorityQueue if you would prefer to work at a lower level.

How to use Win32's BitBlt using Ruby?

Does anyone know how to use Win32's BitBlt() using Ruby? It seems like you need to use a destination DC (device context) and how can Ruby handle that? I use GetPixel() and it is really slow even to get 100 pixels (takes about 10 seconds). thanks.
Second Carl's other post: use win32 screenshot http://github.com/jarmo/win32screenshot
How about writing all of your image processing code in C++ as a Win32 executable and launching it as a separate process or calling into it from Ruby using the Win32API class? It makes sense to do it this way instead of writing a cludge in Ruby which will never perform as well.
I'd just like to note that I'm seeing a similar thing. GetPixel is exceedingly slow on Vista. I've determined that this is the case when you're using that Aero thing. If you set desktop theme to one of the "Classic" settings, it's fast again. And the OP's estimate of ~10 seconds is not wrong, believe it or not. It's really exceedingly slow.
I, too, am looking for a BitBlt in Ruby. I expect I'll need to figure it out/write it, but was hoping someone else has already posted an example.
I wouldn't go quite as far as Ed; chances are you only want to do some relatively simple and commonplace things that a normal GUI would do. For this, such libraries already exist and don't need to be written.
One example would be wxRuby.
I'm afraid I'm not familiar with it, but maybe it already offers some screen-grabbing utility methods.

is using threads and ruby mechanize safe?

Does anyone ever see a lot of errors like this:
Exception `Net::HTTPBadResponse' at /usr/lib/ruby/1.8/net/http.rb:2022
- wrong status line: _SOME HTML CODE HERE_
When using threads and mechanize? I'm relatively certain that this is
some bad behavior between threads and the net/http library, but does
anyone have any advice as far as the upper limit of threads you want
to run at once when using mechanize/nethttp? And how can I capture this kind of exception because rescue Net::HTTPBadResponse doesn't work?
This could be something non-thread-safe in Mechanize, but I can think of other bugs that might cause the same problem. I'd start by disabling persistent connections, if you're using them. The next thing to do is to look at your code, and make sure that you're being careful with the objects you handle. If your application has multiple threads mucking about with common objects, that can break a library that would be otherwise thread-safe.
If there is a threading problem somewhere, the upper limit of threads you can use safely is 1. Any more, and you're just making a trade-off about how often you want the problem to occur, rather than whether it occurs or not.
Based on my grueling experience this evening trying to get two Mechanize-based tasks run in tandem in Event Machine and this somewhat ancient exchange, no, it seems it is not thread-safe.
According to this email by Aaron Patterson himself, if you don't share an agent between threads, you should be OK.
IMHO, this means Mechanize is not thread-safe.

NSThread or pythons' threading module in pyobjc?

I need to do some network bound calls (e.g., fetch a website) and I don't want it to block the UI. Should I be using NSThread's or python's threading module if I am working in pyobjc? I can't find any information on how to choose one over the other. Note, I don't really care about Python's GIL since my tasks are not CPU bound at all.
It will make no difference, you will gain the same behavior with slightly different interfaces. Use whichever fits best into your system.
Learn to love the run loop. Use Cocoa's URL-loading system (or, if you need plain sockets, NSFileHandle) and let it call you when the response (or failure) comes back. Then you don't have to deal with threads at all (the URL-loading system will use a thread for you).
Pretty much the only time to create your own threads in Cocoa is when you have a large task (>0.1 sec) that you can't break up.
(Someone might say NSOperation, but NSOperationQueue is broken and RAOperationQueue doesn't support concurrent operations. Fine if you already have a bunch of NSOperationQueue code or really want to prepare for working NSOperationQueue, but if you need concurrency now, run loop or threads.)
I'm more fond of the native python threading solution since I could join and reference threads around. AFAIK, NSThreads don't support thread joining and cancelling, and you could get a variety of things done with python threads.
Also, it's a bummer that NSThreads can't have multiple arguments, and though there are workarounds for this (like using NSDictionarys and NSArrays), it's still not as elegant and as simple as invoking a thread with arguments laid out in order / corresponding parameters.
But yeah, if the situation demands you to use NSThreads, there shouldn't be any problem at all. Otherwise, it's cool to stick with native python threads.
I have a different suggestion, mainly because python threading is just plain awful because of the GIL (Global Interpreter Lock), especially when you have more than one cpu core. There is a video presentation that goes into this in excruciating detail, but I cannot find the video right now - it was done by a Google employee.
Anyway, you may want to think about using the subprocess module instead of threading (have a helper program that you can execute, or use another binary on the system. Or use NSThread, it should give you more performance than what you can get with CPython threads.

OS X inter thread communication question

I am developing a multi-threaded application in Cocoa. The main thread takes values from the user, and when a button is clicked I invoke a secondary thread in which a long calculation takes place. Now from this thread I have to return the output of every step of the calculation to the main thread. I want to periodically send data from one thread to the other. I can't find any simple example that does this. Any ideas?
There are a number of ways to do this, in rough order of complexity (easiest first):
use NSObject's performSelectorOnMainThread:withObject:waitUntilDone: which is pretty self explanatory.
use performSelector:onThread:withObject:waitUntilDone:, which will let you go the other way
use an NSNotification (and NSDistributedNotificationCenter), though you can easily run into a race condition if you're not careful
Use NSPorts to send data back and forth
Check out the doc that Abizer mentioned for details on all of these.
performSelectorOnMainThread:withObject:waitUntilDone: is often the easiest way to update the UI with a background thread's progress. You could also create your own storage area that's safe to access between threads using NSLock or a similar mechanism, or even use distributed objects (which also works between processes or over a network).
Then there's NSOperationQueue and NSOperation which does help a lot to simplify multi-threaded programming, although a lot of programmers have been avoiding it since it can cause a crash in certain circumstances under Leopard.
Have a look at the Apple docs for this.
You may need to create an ADC member account, but this is free
Multi-threaded Cocoa Programs

Resources