ReleaseSemaphore does not release the semaphore

前端 未结 5 1034
说谎
说谎 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:37

    the problem happens in the following case:

    the main thread resumes the worker threads:

      for (int i=0 ; i

    the worker threads do their work and release the semaphore:

      for (int i=1 ; i

    the main thread waits for all worker threads and resets the semaphore:

      for (int i=0 ; i

    the main thread goes into the next round, trying to resume the worker threads (note that the worker threads haven't event suspended themselves yet! this is where the problem starts... you are trying to resume threads that aren't necessarily suspended yet):

      for (int i=0 ; i

    finally the worker threads suspend themselves (although they should already start the next round):

      SuspendThread(ids[(int) lpParameter]);
    

    and the main thread waits forever since all workers are suspended now:

      for (int i=0 ; i

    here's a link that shows how to correctly solve producer/consumer problems:

    http://en.wikipedia.org/wiki/Producer-consumer_problem

    also i think critical sections are much faster than semaphores and mutexes. they're also easier to understand in most cases (imo).

提交回复
热议问题