honghao0 2010-03-17
Python Library作为计算机语言中常用的语言,很多人都会接触到Python Library中的Semaphore这一计算机语言,一下的文章就是对其实际应用操作方案的具体介绍,希望你浏览完以下的文章会对你有所帮助。
Python Library Semaphore和 .NET Semaphore 一样,限制可同时访问某一资源的线程数。
lock = Semaphore(2) def test(): with lock: for i in range(5): print currentThread().name, i sleep(1) for i in range(5): Thread(target = test).start()
输出:
$ ./main.py
Thread-1 0 <--- Thread-1 和 Thread-2 获得锁
Thread-2 0 Thread-1 1 Thread-2 1 Thread-1 2 Thread-2 2 Thread-1 3 Thread-2 3 Thread-1 4 Thread-2 4
Thread-3 0 <--- Thread-3 和 Thread-4 获得锁
Thread-4 0 Thread-3 1 Thread-4 1 Thread-3 2 Thread-4 2 Thread-3 3 Thread-4 3 Thread-3 4 Thread-4 4
Thread-5 0 <--- Thread-5 获得锁