I have a ruby script that reads data from a serial port.
That data might be some raw binary string that represents a specific protocol datagram (i'm trying XBee API as now).
this data has to be processed in a long run of method calls, something like:
res = @xbee.getresponse
rescue => e
puts e #append to some log here or something
You can just spin off a thread each time you get more data.
def do_work res # parse, transform, insert, etc. end def read_loop loop do begin res = @xbee.getresponse Thread.new(res, &method(:do_work)) rescue => e # ... end end end
do_work method touches some common resource (a log, a database, stdout, etc.) you will need to protect that resource with a Mutex to prevent the different threads from stepping on each other. Also note that Ruby isn't truly multithreaded, so while this will achieve your goal of quickly returning to get more data, it will not actually offer a processing speedup.