我有一个包含这个概念的任务,但我不知道如何实现它。
基本的想法是,我们有一个电影院,有X个座位,Y个人(线程)逐渐到达电影院,想看电影,我需要有一个屏障,等待X个人到达电影院,然后让他们进去看电影,直到最后一个人离开电影院(他们不会立即全部离开,而是逐渐地),然后检查是否有足够的人(X)聚集在电影院外,开始下一个电影节,是否有足够的人让他们进来,如果没有,请X个人聚集,然后让他们进来。
发布于 2020-07-25 16:56:51
这个简单的伪代码应该足以指导你。这三个信号量需要初始化为0。您应该生成单个Theater_thread和多个Person_thread。
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
}
}需要的API调用:
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 (用于信号量P操作和线程连接):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
要将信号量计数减少特定数量,请使用for循环。
https://stackoverflow.com/questions/63086080
复制相似问题