Python学习笔记- Python threading模块
生活随笔
收集整理的這篇文章主要介紹了
Python学习笔记- Python threading模块
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python threading模塊
直接調用
# !/usr/bin/env python # -*- coding:utf-8 -*- import threading import timedef sayhi(num):print("running on number:%s" % num)time.sleep(3)if __name__ =='__main__':#生成兩個線程實例t1 = threading.Thread(target=sayhi,args=(1,))t2 = threading .Thread(target = sayhi,args=(2,))#啟動兩個線程 t1.start()t2.start()#打印線程名print(t1.getName())print(t2.getName())繼承調用
?
import threading import time class MyThread(threading.Thread):def __init__(self,num):# super(Mythread,self).__init__(self)threading.Thread.__init__(self)self.num = numdef run(self):print('running on number%s' %self.num)time.sleep(3)if __name__ == '__main__':t1 = MyThread(1)t2 = MyThread(2)t1.start()t2.start()批量處理多線程及等待
import threading import timedef sayhi(num):print('running on number%s' %num)time.sleep(5)if __name__ == '__main__':'''t1 = MyThread(1)t2 = MyThread(2)t1.start()t2.start()''' t_list=[] #用于存儲實例 for i in range(100):t = threading.Thread(target=sayhi,args =[i,] ) #循環創建實例 t.start()t_list.append(t) #將創建的實力添加到列表 for i in t_list:#循環列表中的創建的實例i.join() #在每個列表后面添加等待 print('##############main###############')?
守護線程(Daemon)?
import threading import timedef run(n):print('--------runnig----------')time.sleep(200)print('--------done------------')def main(self):for i in range(5):t = threading.Thread(target=run,args=[i,])t.start()t.join()print('start thread',t.getName()) m = threading.Thread(target=main,args=[]) m.setDaemon(True)#將主線程設置為Daemon線程,它退出時,其它子線程會同時退出,不管是否執行完任務 m.start() print('-----main thread done-----')?
線程鎖(互斥鎖Mutex)
# !/usr/bin/env python # -*- coding:utf-8 -*- import threading import time def addNum():global num #在每個進程中都獲得這個全局變量print('----get num:%s' %num)time.sleep(2)lock.acquire()#修改數據前加鎖num-=1lock.release()#修改后釋放鎖 num = 100 thread_list=[] lock = threading.Lock() #生成全局鎖 for i in range(100):t=threading.Thread(target=addNum)t.start()thread_list.append(t)for t in thread_list:t.join() #等待所有線程執行完畢print('final Num:%s'%num)?
遞歸鎖(RLock)
# !/usr/bin/env python # -*- coding:utf-8 -*- import threading,timedef run1():print("grab the first part data")lock.acquire()global numnum +=1lock.release()return num def run2():print("grab the second part data")lock.acquire()global num2num2+=1lock.release()return num2 def run3():lock.acquire()#加遞歸鎖res = run1() #調用run1方法print('--------between run1 and run2-----')res2 = run2()#調用run2方法lock.release()#釋放遞歸鎖print(res,res2)if __name__ == '__main__':num,num2 = 0,0 #初始化變量lock = threading.RLock()#創建線程鎖for i in range(10):t = threading.Thread(target=run3) #創建線程 t.start()while threading.active_count() != 1:#判斷是否只剩一個線程print(threading.active_count()) else:print('----all threads done---')print(num,num2)Semaphore(信號量)
互斥鎖 同時只允許一個線程更改數據,而Semaphore是同時允許一定數量的線程更改數據.
# !/usr/bin/env python # -*- coding:utf-8 -*-import threading,timedef run(n):semaphore.acquire()time.sleep(1)print("run the thread: %s\n" %n)semaphore.release()if __name__ == '__main__':num= 0semaphore = threading.BoundedSemaphore(3) #最多允許5個線程同時運行for i in range(20):t = threading.Thread(target=run,args=(i,))t.start()while threading.active_count() != 1:pass #print threading.active_count() else:print('----all threads done---')print(num)?
線程間同步和交互Event
An event is a simple synchronization object;
the event represents an internal flag, and threads
can wait for the flag to be set, or set or clear the flag themselves.
通過Event來實現兩個或多個線程間的交互
Event = threading.Event()?
even.wait()?
event.set()
event.clear()
實例:
import threading,time def light():if not event.isSet():event.set() #wait就不阻塞 #綠燈狀態count = 0while True:if count < 10:print('\033[42;1m--green light on---\033[0m')elif count <13:print('\033[43;1m--yellow light on---\033[0m')elif count <20:if event.isSet():event.clear()print('\033[41;1m--red light on---\033[0m')else:count = 0event.set() #打開綠燈time.sleep(1)count +=1 def car(n):while 1:time.sleep(1)if event.isSet(): #綠燈print("car [%s] is running.." % n)else:print("car [%s] is waiting for the red light.." %n)event.wait() if __name__ == '__main__':event = threading.Event()Light = threading.Thread(target=light)Light.start()for i in range(3):t = threading.Thread(target=car,args=(i,))t.start()?
轉載于:https://www.cnblogs.com/luoye00/p/5281914.html
總結
以上是生活随笔為你收集整理的Python学习笔记- Python threading模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Object-c 类、对象方法
- 下一篇: python面对对象编程-------5