ReleaseSemaphore does not release the semaphore

前端 未结 5 1016
说谎
说谎 2020-12-01 23:18

(In short: main()\'s WaitForSingleObject hangs in the program below).

I\'m trying to write a piece of code that dispatches threads and waits for them to finish befor

5条回答
  •  天命终不由人
    2020-12-01 23:42

    Here is a practical solution.

    I wanted my main program to use threads (then using more than one core) to munch jobs and wait for all the threads to complete before resuming and doing other stuff. I did not want to let the threads die and create new ones because that's slow. In my question, I was trying to do that by suspending the threads, which seemed natural. But as nobugz pointed out, "Thou canst control threading with Suspend/ReleaseThread()".

    The solution involves semaphores like the one I was using to control the threads. Actually one more semaphore is used to control the main thread. Now I have one semaphore per thread to control the threads and one semaphore to control the main.

    Here is the solution:

    #include 
    #include 
    #include 
    #include 
    
    #define TRY  500000
    #define LOOP 100
    
    HANDLE *ids;
    HANDLE *semaphores;
    HANDLE allThreadsSemaphore;
    
    DWORD WINAPI Count(__in LPVOID lpParameter)
    {   
        float x = 1.0f;         
        while(1)
        {   
            WaitForSingleObject(semaphores[(int)lpParameter],INFINITE);
            for (int i=1 ; i

提交回复
热议问题