python多线程并行编程_Python并行编程(二):基于线程的并行
1、介紹
軟件應(yīng)用中使用最廣泛的并行編程范例是多線程。通常一個應(yīng)用有一個進程,分成多個獨立的線程,并行運行、互相配合,執(zhí)行不同類型的任務(wù)。
線程是獨立的處理流程,可以和系統(tǒng)的其他線程并行或并發(fā)地執(zhí)行。多線程可以利用共享內(nèi)存空間共享數(shù)據(jù)和資源。線程和進程的具體實現(xiàn)取決于你要運行的操作系統(tǒng),但是總體來講,我們可以說線程是包含在進程中的,同一個進程的多個不同的線程可以共享相同的資源,而進程之間不會共享資源。
每一個線程基本上包含3個元素:程序計數(shù)器,寄存器和棧。與同一進程的其他線程共享的資源基本上包括數(shù)據(jù)和系統(tǒng)資源。每一個線程也有自己的運行狀態(tài),可以和其他線程同步,線程的狀態(tài)大體上可以分為ready,running,blocked。線程的典型應(yīng)用是應(yīng)用軟件的并行化,目的是為了充分利用現(xiàn)代的多核處理器,使每個核心可以運行單個線程。相比于進程,使用線程的優(yōu)勢主要是性能,相比之下,在進程之間切換上下文要比在統(tǒng)一進程的多線程之間切換上下文要重的多。
2、定義一個線程
使用線程最簡單的方式是用一個目標(biāo)函數(shù)實例化一個Thread然后調(diào)用start()方法啟動它。Python的threading模塊提供了Thread()方法在不同的線程中運行函數(shù)或處理過程等。
class threading.Thread(group=None, ?target=None, name=None, args=(), kwargs={})
- group:特性預(yù)留
- target:當(dāng)線程啟動的時候要執(zhí)行的函數(shù)
- name:線程的名字,默認為Thread-N
- args:傳遞給target的參數(shù),要試用tuple類型
- kwargs:同上,試用字段類型dict
線程代碼用例:
importthreadingdeffunction(i):print("I am thread-%s" %i)returnthreads=[]for i in range(5):
t= threading.Thread(target=function, args=(i,))
threads.append(t)
t.start()
t.join()
t.join:主線程會調(diào)用t線程,然后等待t線程完成再執(zhí)行for循環(huán)開啟下一個t線程。可理解為阻塞主線程。
3、確認一個線程
使用參數(shù)來確認或命名線程是沒有必要的,每一個Thread實例創(chuàng)建的時候都有一個帶默認值的名字,并且可以修改。在服務(wù)端通常一個服務(wù)進程都有多個線程服務(wù),負責(zé)不同的操作,這時候命名線程是很實用的。
自定義線程名稱用例:
importthreadingimporttimedeffirst_function():print("%s is starting" %threading.currentThread().getName())
time.sleep(2)print("%s is exiting" %threading.currentThread().getName())defsecond_function():print("%s is starting" %threading.currentThread().getName())
time.sleep(2)print("%s is exiting" %threading.currentThread().getName())defthird_function():print("%s is starting" %threading.currentThread().getName())
time.sleep(2)print("%s is exiting" %threading.currentThread().getName())if __name__ == "__main__":
t1= threading.Thread(name='first_function', target=first_function)
t2= threading.Thread(name='second_function', target=second_function)
t3= threading.Thread(name='third_function', target=third_function)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
運行結(jié)果:
如果不自定義名稱如下:
importthreadingimporttimedeffirst_function():print("%s is starting" %threading.currentThread().getName())
time.sleep(2)print("%s is exiting" %threading.currentThread().getName())defsecond_function():print("%s is starting" %threading.currentThread().getName())
time.sleep(2)print("%s is exiting" %threading.currentThread().getName())defthird_function():print("%s is starting" %threading.currentThread().getName())
time.sleep(2)print("%s is exiting" %threading.currentThread().getName())if __name__ == "__main__":#t1 = threading.Thread(name='first_function', target=first_function)
#t2 = threading.Thread(name='second_function', target=second_function)
#t3 = threading.Thread(name='third_function', target=third_function)
t1= threading.Thread(target=first_function)
t2= threading.Thread(target=second_function)
t3= threading.Thread(name='third_function', target=third_function)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
運行結(jié)果:
4、使用線程
在子類中實現(xiàn)線程:
importthreadingimporttime
exit_flag=0classmyThread(threading.Thread):def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID=threadID
self.name=name
self.counter=counterdefrun(self):print("Starting %s" %self.name)
print_time(self.name, self.counter,5)print("Exiting %s" %self.name)defprint_time(threadName, delay, counter):whilecounter:ifexit_flag:import_thread
_thread.exit()
time.sleep(delay)print("%s:%s" %(threadName, time.ctime(time.time())))
counter-= 1
#創(chuàng)建實例
thread1 = myThread(1, "Thread-1", 1)
thread2= myThread(2, "Thread-2", 2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()print("Exiting Main Thread")
運行結(jié)果如下:
線程模塊是創(chuàng)建和管理線程的首選形式。每一個線程都通過一個集成Thread的子類代表,覆蓋run()方法來實現(xiàn)邏輯,這個方法是線程的入門,執(zhí)行start()即調(diào)用此方法。
總結(jié)
以上是生活随笔為你收集整理的python多线程并行编程_Python并行编程(二):基于线程的并行的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: axure 如何设置选项联动_Axure
- 下一篇: python慢在哪里_求大神分析一下我的