Bad code:
thread do
worker = Worker.new
for x = 0 to max
worker.do_item(x)
end
end
Good code:
worker = Worker.new
timer do
if worker.fetch_next_item
worker.do_current_item
else
stop_timer
end
end
The latter is an example of ActionChunking. The worker object is more EventDriven. It maintains its own current index, and does not rely on an external loop statement to maintain its current state.
To avoid PrematureConcurrency, if you think you must thread, always try action chunking first (or try selecting from an array of mutex semaphores!). If you then prove you need a thread (per ConcurrencyVsXp), you will probably be better off using the action-chunked version of the design:
thread do
worker = Worker.new
while worker.index < worker.max
worker.do_current_item
end
end
One common (bad) tutorial example of threading is hiding a long process from a GUI. In many situations, the ActionChunked version is more flexible, using the GUI's timer facility for its pump. Such a process is very easy to upgrade with a
- cancel button
- progress bar
- restart button
- realtime log or transcript
- exception handler.