我正试图绕着信号量以及它们是如何工作但无济于事。我有一个关于作业的问题
考虑下面显示的信号量算法。
semaphore S <- 1, T <- 0
p q
p1: wait (S) q1: wait (T)
p2: write (“p”) q2: write (“q”)
p3: signal (T) q3: signal (S)
a. What are the possible outputs for this algorithm?
有人能引导我朝正确的方向找出如何解决这个问题吗?
答案 0 :(得分:2)
sem_wait() decrements (locks) the semaphore pointed to by sem. If the semaphore's value is greater than zero, then the decrement proceeds, and the function returns, immediately. If the semaphore currently has the value zero, then the call blocks until either it becomes possible to perform the decrement (i.e., the semaphore value rises above zero), or a signal handler interrupts the call.
http://man7.org/linux/man-pages/man3/sem_wait.3.html
如果信号量包含大于1的值,则进程调用wait可以继续而不会阻塞。当等待调用返回时,信号量值减少一个限制数量的进程/线程,可以进入信号量受保护的代码块。
代码中的初始状态只能输出&#34; pq&#34;因为线程p在第一次等待调用中继续而没有阻塞线程q阻塞在第一次等待,直到线程p调用信号(T)。信号调用会增加信号量。如果在信号调用时,信号量的值为0并且存在阻塞线程,则其中一个线程返回运行状态。
警告:在块的开始和结束时为不同的信号量调用wait和signal是个坏主意。很容易导致导致竞争条件或死锁的复杂状态多线程状态转换。在说我不得不承认在单元测试中以非常类似的方式使用信号量来控制两个ipc进程的操作顺序。