python threading 两种创建方式
生活随笔
收集整理的這篇文章主要介紹了
python threading 两种创建方式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
作用:建立在thread模塊之上,可以更容易地管理多個執(zhí)行線程。
通過使用線程,程序可以在同一個進程空間并發(fā)地運行多個操作。threading模塊建立在thread的底層特性基礎上,可以更容易地完成線程處理。
?
1、調用函數(shù)
要使用Thread,最簡單的方法就是用一個目標函數(shù)實例化一個Thread對象,并調用start()讓它開始工作。
1 import threading 2 3 def worker(num): 4 print 'worker' 5 return 6 7 threads = [] 8 for i in range(5): 9 t = threading.Thread(target=worker, args=(i,)) 10 threads.append(t) 11 t.start?
2、派生進程
開始時,Thread要完成一些基本初始化,然后調用其run()方法,這會調用傳遞到構造函數(shù)的目標函數(shù)。要創(chuàng)建Thrad的一個子類,需要覆蓋run()來完成所需的工作。
1 import threading 2 import logging 3 4 logging.basicConfig(level=logging.DEBUG, 5 format='(%(threadName)-10s) %(message)s', 6 ) 7 8 class MyThread(threading.Thread): 9 10 def run(self): 11 logging.debug('running') 12 return 13 14 for i in range(5): 15 t = MyThread() 16 t.start()?
參考:
《python 標準庫》 10.3.5 派生線程(p412)
轉載于:https://www.cnblogs.com/congbo/archive/2012/08/23/2652381.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結
以上是生活随笔為你收集整理的python threading 两种创建方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 工程结构,它到底是怎么运
- 下一篇: python网络编程-一些常用有用的函数