python多线程同步机制Semaphore
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python多线程同步机制Semaphore相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Python 线程同步机制:Semaphore """ import time import threading import random # 信号量同步基于内部计数器,每调用一次acquire(),计数器减1;每调用一次release(),计数器加1.当计数器为0时,acquire()调用被阻塞。 sema = threading.Semaphore(3) def foo(param): with sema: print ‘%d acquire sema‘ % (param,) n = random.random() * 3 time.sleep(5) print ‘%d releas sema‘ % (param,) if __name__ == ‘__main__‘: threads = [] for i in range(5): t = threading.Thread(target=foo, args=(i,)) t.start() threads.append(t) print ‘------------‘ for t in threads: t.join() print ‘main End‘
输出:
python t_Semaphore.py
0 acquire sema
1 acquire sema
2 acquire sema
------------
1 releas sema
2 releas sema
0 releas sema3 acquire sema
4 acquire sema
4 releas sema
3 releas sema
main End
Process finished with exit code 0
以上是关于python多线程同步机制Semaphore的主要内容,如果未能解决你的问题,请参考以下文章