python3 线程信号量semaphore
# -*- coding: utf-8 -*-
import time
from threading import Thread, Semaphore
def go_ktv(i):
print("user%s正在....ktv." % (i))
time.sleep(2)
if __name__ == '__main__':
'''开启20个线程的运行时间,一个cpu并发执行20个线程,执行时间是最长线程执行的时间'''
start_time = time.time()
p_lst = []
for i in range(20):
p = Thread(target=go_ktv, args=(i,))
p.start()
p_lst.append(p)
[pp.join() for pp in p_lst]
print("运行时间:%s" % (time.time() - start_time))
# user0正在....ktv.
# user1正在....ktv.
# user2正在....ktv.
# user3正在....ktv.
# user4正在....ktv.
# user5正在....ktv.
# user6正在....ktv.
# user7正在....ktv.
# user8正在....ktv.
# user9正在....ktv.
# user10正在....ktv.
# user11正在....ktv.
# user12正在....ktv.
# user13正在....ktv.
# user14正在....ktv.
# user15正在....ktv.
# user16正在....ktv.
# user17正在....ktv.
# user18正在....ktv.
# user19正在....ktv.
# 运行时间:2.0061147212982178
# -*- coding: utf-8 -*-
import time
from threading import Thread, Semaphore
def go_ktv(i):
sem.acquire()
print("user%s正在....ktv." % (i))
time.sleep(2)
sem.release()
if __name__ == '__main__':
'''线程加信号量,线程本身是并发执行的,加了信号量,相当于又加了一把互斥锁,并发执行5(信号量大小)个线程'''
start_time = time.time()
sem = Semaphore(5)
p_lst = []
for i in range(20):
p = Thread(target=go_ktv, args=(i,))
p.start()
p_lst.append(p)
[pp.join() for pp in p_lst]
print("运行时间:%s" % (time.time() - start_time))
# user0正在....ktv.
# user1正在....ktv.
# user2正在....ktv.
# user3正在....ktv.
# user4正在....ktv.
# user5正在....ktv.
# user7正在....ktv.
# user6正在....ktv.
# user8正在....ktv.
# user9正在....ktv.
# user10正在....ktv.
# user12正在....ktv.
# user11正在....ktv.
# user13正在....ktv.
# user14正在....ktv.
# user16正在....ktv.
# user15正在....ktv.
# user17正在....ktv.
# user18正在....ktv.
# user19正在....ktv.
# 运行时间:8.002457857131958