Repeating Barrier In Synchronized Programming In C Win32 Api
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.
Answer
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_thread
s.
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:
CreateThread: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread
CreateSemaphore: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createsemaphorea
WaitForSingleObject (for semaphore P operation and thread join): https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-registerwaitforsingleobject
ReleaseSemaphore: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-releasesemaphore
To decrease the semaphore count by a specific amount, use a for loop.
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page