I'm working on an application that plays music.
During playback, often things need to happen on separate threads because they need to happen simultaneously. For example, the notes of a chord need to be heard together, so each one is assigned its own thread to be played in. (Edit to clarify: calling note.play() freezes the thread until the note is done playing, and this is why I need three separate threads to have three notes heard at the same time.)
This kind of behavior creates many threads during playback of a piece of music.
For example, consider a piece of music with a short melody and short accompanying chord progression. The entire melody can be played on a single thread, but the progression needs three threads to play, since each of its chords contains three notes.
So the pseudo-code for playing a progression looks like this:
void playProgression(Progression prog){
for(Chord chord : prog)
for(Note note : chord)
runOnNewThread( func(){ note.play(); } );
}
So assuming the progression has 4 chords, and we play it twice, than we are opening 3 notes * 4 chords * 2 times = 24 threads. And this is just for playing it once.
Actually, it works fine in practice. I don't notice any noticeable latency, or bugs resulting from this.
But I wanted to ask if this is correct practice, or if I'm doing something fundamentally wrong. Is it reasonable to create so many threads each time the user pushes a button? If not, how can I do it differently?
Is it reasonable to create so many threads...depends on the threading model of the language. Threads used for parallelism are often handled at the OS level so the OS can map them to multiple cores. Such threads are expensive to create and switch between. Threads for concurrency (interleaving two tasks, not necessarily executing both simultaneously) can be implemented at the language/VM level and can be made extremely "cheap" to produce and switch between so you can, say, talk to 10 network sockets more or less simultaneously, but you won't necessarily get more CPU throughput that way. – Doval Aug 26 '14 at 11:48