[已软注销]对《The Little Book of Semaphores, 2nd Edition》的笔记(2)

The Little Book of Semaphores, 2nd Edition
  • 书名: The Little Book of Semaphores, 2nd Edition
  • 作者: Allen B. Downey
  • 副标题: The Ins and Outs of Concurrency Control and Common Mistakes
  • 页数: 294
  • 出版社: CreateSpace Independent Publishing Platform
  • 出版年: 2009-3-20
  • 第3页 Serialization with messages
    Two events are concurrent if we cannot tell by looking at the program which will happen first. Sometimes we can tell, after the program runs, which happened first, but often not, and even if we can, there is no guarantee if we will get the same result the next time.
    引自 Serialization with messages
    2012-12-07 15:15:33 回应
  • 3.8.2 FIFO

    3.8.2节有错,这节的题目是用Semaphore实现FIFO的Semaphore,给出的最后答案是:

    class Fifo:
    	def __init__(self):
    		self.queue= Queue()
    		self.mutex = Semaphore(1)
    
    	def wait():
    		self.mutex.wait()
    		self.queue.add(mySem)
    		sekf.mutex.signal()
    		mySem.wait()
    
    	def signal():
    		self.mutex.wait()
    		sem = self.queue.remove()
    		self.mutex.signal()
    		sem.signal()

    给出题目时要求我们不要把Queue的操作当作thread-safe的,所以需要mutex来保护queue的操作,但是python的Queue的出队列方法有一个特殊的语义:如果队列为空,调用出队操作的进程阻塞,这样一来上面的程序就会造成死锁:在可能阻塞的操作里得到一个mutex,而之后入队线程又必须获得这个mutex。所以这个类只能一个一个入队完之后才能一个一个出队。所以这个类在实际中没什么作用。 这样来说这本书里的内容实在是对实际的编程没有什么作用,最大的作用恐怕就是锻炼下思维以及在面试之前看看了吧。 ps. 就不吐槽mySem根本没有初始化直接使用,也不吐槽类的方法连self参数都没有,也不吐槽python里Queue的方法和Semaphore的方法名根本就不对(不过Semaphore的方法名竟然是acquire和release就是python的不对了)

    2012-12-10 12:11:43 1回应