I include a timeout on the WaitOne() before checking remaining again to protect against the rare case where the last outstanding thread decrements 'remaining' and then signals completion between the main thread checking 'remaining' and waiting for the next completion signal, which would otherwise result in the main thread missing the last signal and locking forever. This is faster than just using Thread.Sleep(10)Thread.Sleep(10) because it has a chance to return immediately after the last thread completes.
My #1 goal is to ensure thread safety. I want to be sure I won't accidentally return too early (before all elements have been acted on), and be sure that I don't become deadlocked or otherwise stuck.
My #2 goal is to add as little overhead as possible - minimizing amount of time that fewer than MAX_CONCURRENT threads are executing action, and returning as soon as possible after the final action has been performed.Goals:
Any help is greatly appreciated.
Ensure thread safety - I want to be sure I won't accidentally return too early (before all elements have been acted on), and be sure that I don't become deadlocked or otherwise stuck.
Add as little overhead as possible - minimizing amount of time that fewer than
MAX_CONCURRENTthreads are executingaction, and returning as soon as possible after the finalactionhas been performed.