2015-11-17 31 views
-1

我试图围绕信号量和他们如何工作,但无济于事。我对一个任务有一个疑问信号量算法的可能输出

考虑下面显示的信号量算法。

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? 

有人能带我正确的方向找出如何解决这个问题吗?

回答

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可以继续而不会阻塞。当等待调用返回信号量值已经减少了一个限制数量的进程/线程可以进入信号量受保护的代码块。

代码中的初始状态只产生可能的输出“pq”,因为线程p在第一次等待调用时不会阻塞。线程q首先等待线程p调用信号(T)。信号调用增加了信号量。如果在信号调用信号量为0时有阻塞线程在等待它,则其中一个线程返回到运行状态。

警告:在块的开始和结束处调用wait和signal来获取不同的信号量是个坏主意。很容易导致复杂的状态多线程状态转换导致竞争条件或死锁。在说我不得不承认在单元测试中以非常相似的方式使用信号量来控制两个ipc进程的操作顺序。

+0

由于值递减不会输出为“ppq”,因为它先用p,那么S将被设置为0,再次运行p,然后解除q和q的运行? – ryandonohue

+0

我明白在伪代码中没有循环。如果你的意思是p和q都在(真)永久循环中运行,那么你总是会得到“pqpqpq ...”。这是因为p线程将在第二次调用中阻塞以等待(S),直到线程q在写入“q”之后调用信号(S)。 –