Repeating Barrier In Synchronized Programming In C Win32 Api

- 1 answer

I have a task that includes this concept and I have no idea how to implement it.

The basic idea is we have a movie theater that has X seats and Y people (threads) who gradually arrive at the movie theater and want to watch the movie, I need to have a barrier that waits for X people to reach the movie theater, then let them in to watch the movie and wait till the last person leaves the movie theater (they don't leave all at once but gradually) then check if enough people (X) have gathered outside the movie theater to start the next movie session and if there is enough to let them in and if not wait for X people to gather and then let them in.



This simple pseudocode should be enough to guide you. The three semaphores need to be initialized with 0. You should spawn a single Theater_thread and multiple Person_threads.

Person_thread() {
    sem1.V(1)   // Arrive at theater
    sem2.P(1)   // Wait to be let in
    sleep(1000) // Watch movie
    sem3.V(1)   // Leave the theater

Theater_thread() {
    while (1) {
        sem1.P(X)   // Wait for X persons to arrive
        sem2.V(X)   // Let X persons to enter
        sem3.P(X)   // Wait for all persons to leave

Needed API calls:



WaitForSingleObject (for semaphore P operation and thread join):


To decrease the semaphore count by a specific amount, use a for loop.