asynchronousvectorsynchronizationwaitforsingleobjectwaitformultipleobjects

What are the benefits of using WaitForMultipleObjects instead of WaitForSingleObject in a loop?


I have a vector<HANDLE>. I want to wait for all of them to finish. I don't want to copy them over to an array. What are the benefits of doing so anyway and using WaitForMultpleObjects, rather than using WaitForSingleObject in a loop if any?

Thanks!


Solution

  • First, in every C++ compiler I know of, vectors are internally an array, and you can get a pointer to the array with &yourvector[0]. In C++11 I believe this behavior is also required by the standard. So there's no need to copy.

    As for the benefit, WaitForMultipleObjects will reduce the number of times you wake up, saving some small amount of CPU time. It will also atomically acquire all of the HANDLEs at the same time - if you have a bunch of mutex or semaphore objects and need to lock them all, this can be important.