Subj : Re: Threading strategy To : comp.programming.threads From : Joe Seigh Date : Thu Apr 07 2005 01:10 pm On 7 Apr 2005 07:24:09 -0700, wrote: > Hi, > > I'm writing process operating software and I have a question regarding > Multi threading strategy. The machine has a couple of subsystems. The > machine produces units, which have to pass these subsystems in > sequential order. Since the time each subsystem takes to complete its > job varies, there are buffers between the subsystems. > > Basically there are two different approaches: > > - Use one thread per unit. The code would look something like this: > > class UnitWorkThread { > void work() { > doSubSystem1(); > waitForSubSystem2(); > doSubSystem2(); > waitForSubSystem3(); > doSubSystem3(); > } > } What do the waitForSubSystem functions do? > > i.e. The lifecycle of this thread resembles the lifecycle of a single > unit of production. > > - The other approach is to use one thread per subsystem. Each subsystem > thread would look something like this: > > class SubsystemThread { > void work() { > waitForUnit(); > doActualWork(); > } > } > > There are advantages to each approach. The second approach uses a > finite, known number of threads so starting, stopping and generally > controlling the state of all subsystems becomes a lot easier. However, > the first approach looks easier to synchronize. > > Furthermore, I haven't got a clue which approach would be better in > terms of performance. > > Is there anyone who has any experience and would like to share a bit of > wisdom? > The thread per work unit is the more natural approach. The second approach, producer/consumer is more efficient if you have lots of work, can encode task state, and the OS/hardware handling of the thread stack is suboptimal (they all are). There's a bit of trade off on cache usage on keeping task data with one thread vs. the more local code usage of producer/consumer. The suboptimal stack implementations are usually the deciding factor. -- Joe Seigh .