Python多線程編程(二):啟動線程的兩種方法
在Python中我們主要是通過thread和threading這兩個模塊來實現(xiàn)的,其中Python的threading模塊是對thread做了一些包裝的,可以更加方便的被使用,所以我們使用threading模塊實現(xiàn)多線程編程。一般來說,使用線程有兩種模式,一種是創(chuàng)建線程要執(zhí)行的函數(shù),把這個函數(shù)傳遞進Thread對象里,讓它來執(zhí)行;另一種是直接從Thread繼承,創(chuàng)建一個新的class,把線程執(zhí)行的代碼放到這個新的 class里。
將函數(shù)傳遞進Thread對象
'''
Created on 2012-9-5
@author: walfred
@module: thread.ThreadTest1
@description:
'''
import threading
def thread_fun(num):
for n in range(0, int(num)):
print " I come from %s, num: %s" %( threading.currentThread().getName(), n)
def main(thread_num):
thread_list = list();
# 先創(chuàng)建線程對象
for i in range(0, thread_num):
thread_name = "thread_%s" %i
thread_list.append(threading.Thread(target = thread_fun, name = thread_name, args = (20,)))
# 啟動所有線程
for thread in thread_list:
thread.start()
# 主線程中等待所有子線程退出
for thread in thread_list:
thread.join()
if __name__ == "__main__":
main(3)
程序啟動了3個線程,并且打印了每一個線程的線程名字,這個比較簡單吧,處理重復任務就派出用場了,下面介紹使用繼承threading的方式;
繼承自threading.Thread類
'''
Created on 2012-9-6
@author: walfred
@module: thread.ThreadTest2
'''
import threading
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self);
def run(self):
print "I am %s" %self.name
if __name__ == "__main__":
for thread in range(0, 5):
t = MyThread()
t.start()
接下來的文章,將會介紹如何控制這些線程,包括子線程的退出,子線程是否存活及將子線程設置為守護線程(Daemon)。
相關文章
python 遺傳算法求函數(shù)極值的實現(xiàn)代碼
今天小編就為大家分享一篇python 遺傳算法求函數(shù)極值的實現(xiàn)代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
pytorch LayerNorm參數(shù)的用法及計算過程
這篇文章主要介紹了pytorch LayerNorm參數(shù)的用法及計算過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python+Matplotlib+LaTeX玩轉數(shù)學公式
這篇文章主要為大家介紹了如何在Matplotlib中使用LaTeX?公式和符號以及Python如何生成LaTeX數(shù)學公式。文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2022-02-02
基于Flask實現(xiàn)一個智能的多語言Hello World服務器
這篇文章主要為大家詳細介紹了如何使用Flask框架創(chuàng)建一個智能的多語言Hello World服務器,能夠自動檢測訪問者的瀏覽器語言設置,需要的可以了解下2025-03-03
Python Opencv實現(xiàn)單目標檢測的示例代碼
這篇文章主要介紹了Python Opencv實現(xiàn)單目標檢測的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09

