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?
Multithreading: am I doing it wrong?
multithreading
One assumption you are making might not be valid: you require (among other things) that your threads execute simultaneously. Might work for 3, but at some point the system is going to need to prioritize which threads to run first, and which one wait.Your implementation will ultimately depend on your API, but most modern APIs will let you tell in advance what you want to play and take care of the timing and queuing themselves. If you were to code such an API yourself, ignoring any existing system API (why would you?!), an event queue mixing your notes and playing them from a single thread looks like a better approach than a thread per note model.