tags:

views:

13

answers:

1

I want to write a program that will constantly compute numbers, and draw on the window canvas, including drawing text and setting pixels. So the program probably cannot go into an event loop (the main_loop), because that will stop the computation of numbers.

  1. Is there a way just to draw the items without an event loop?

  2. Or, should a thread be created, so that one thread will do the computation, and one thread handles the window's event loop?

A: 

The general strategy for event-based programs that must do long calculations is one of the following:

  1. break the calculations into small chunks that take no more than a few 10's of milliseconds, then schedule them to run one after the other when the event loop is idle. Remember: the event loop is just a loop, so if your long running calculation is just a huge loop of tight and fast code let the event loop be your loop.
  2. put the long running calculation in a separate thread and have that thread communicate its results back to the main thread in a thread-safe manner
  3. put the long running calculation in a separate process and have that process send updates back to your main process

The first method is ideal if you can manage it. My personal preference then goes to the third method. IMO threads should be avoided if at all possible, unless you fully grok threaded programming (and even then I still usually recommend a separate process).

Bryan Oakley