1. 程式人生 > >多執行緒互斥鎖訊號量

多執行緒互斥鎖訊號量

例1:執行緒加鎖

import threading
import time
num=0
def run(n):
    lock.acquire()
    global num
    num+=1
    print("task start",n)
    time.sleep(2)
    print("task done=>",n,'num=%d'%num)
    print(threading.current_thread())
    lock.release()
def run1():
    print('hello')
start_time=time.time()
lock=threading.Lock()
for i in range(5):
    t=threading.Thread(target=run,args=('t-%s'%i,))
    t.start()

t1=threading.Thread(target=run1)
print(threading.current_thread())
t1.start()
print(threading.current_thread())
print(threading.active_count())
print(threading.current_thread())
print('cost:',time.time()-start_time)

例2:訊號量

import threading,time
num = 0

def run(n):
    t_sema.acquire()
    print('task start!')
    global num
    num+=1
    print("task done",n,'num=%d'%num)
    time.sleep(2)
    t_sema.release()

t_sema = threading.BoundedSemaphore(5)
l_th=[]
for i in range(20):
    t=threading.Thread(target=run,args=('t->%s'%i,))
    l_th.append(t)
    t.start()

# for i in l_th:
#     i.join()
print(num)
print('DONE')

加鎖和訊號量的本質是相同的,只不過加鎖是一個,訊號量是多個。可參考阮一峰日誌中的講解。