Hello everyone,
I am just learning how to write mutithreaded programs right now and I have a hypothetical question about how many threads are optimal for a program.
Let me describe 2 scenarios.
The first scenario is that i have a program that is easily multi threaded but each thread is going to be doing a lot of work (execution times for each thread is on the order of seconds).
The second scenario is that i have a program that is also easily multi thread but each thread has a very short execution time, on the order of milliseconds.
In either one of these scenarios, what is the most efficient way of mutithreading the programs? Is it either creating as many threads as my system memory will allow, or wait for threads to finish before creating new ones so that I only ever have a maxim of 4 worker threads running at any one time.
On one hand, many threads may have overhead problems with cores switching in between threads (from my understanding, its not such a severe overhead). On the other hand, if I limit the number of threads running, that means that I'll be running extra checking conditions and locking and unlocking a counter variable to keep track of the number of threads running, and creating new threads when old ones finish.
I can see that if there are many small threads, it would be best to simply overload my system with as many threads as possable as since there wont be too much thread switching before a thread finishes running. That would save me the overhead of constantly keeping track of the number of threads.
Also, if there are only a few large threads (by few, i mean a couple hundred or so large ones) it would make sense to keep track of the threads so that we keep the threads at optimal numbers such that there isent very much thread switching (as since the overhead would be greater as we would likely switch many times before a single thread finishes).
So would these assumptions be correct for each case or is there a universal way of doing things that would be correct in all situations?
Note: this is assuming a muti core system (for now, lets ignore hyperthreading) and lets ignore any of the typical problems associated with mutithreading (assume that all threads have private write locations and can only read from public ones, locking and unlocking only happens when incrementing or decrementing the counter for number of active threads).
Thanks,
-Faken