關于Python的Thread線程模塊詳解
Python線程與進程
進程:進程是程序的一次執(zhí)行,每個進程都有自己的地址空間、內存、數據棧以及其他記錄其運行的輔助數據。
線程:所有的線程運行在同一個進程中,共享相同的運行環(huán)境。線程有開始順序執(zhí)行和結束三個部分。
舉例說明:
(1)計算機的核心是CPU,它承擔了所有的計算任務,它就像一座工廠,時刻在運行。
(2)假定工廠的電力有限,一次只能供給一個車間使用,也就是說,一個車間開工的時候,其他工廠度必須要停下來。其背后的意思就是,單個CPU一次只能運行一個任務。
(3)進程就好比工廠的車間,它代表CPU所能處理的單個任務,任意時刻,CPU總是運行一個進程,其他進程處于非運行狀態(tài)。
(4)一個車間里,可以有很多工人,他們協同完成一個任務。
(5)線程就好比車間里的工人,一個進程可以包括多個線程。
Python thread模塊

python threading模塊

python中線程的使用
python中使用線程的方法有兩種:函數、通過類來包裝線程對象
(1)函數式:調用thread模塊中的start_new_thread()函數來產生新的線程。如下例:
import thread
import time
def fun1():
print('Hello world!%s',time.ctime())
def main():
thread.start_new_thread(fun1,())
thread.start_new_thread(fun1,())
time.sleep(2)
if __name__ == '__main__':
main()
thread.start_new_thread(function,args[,kwargs])的第一個參數時線程函數,第二個參數時傳遞給線程函數的參數,它必須是tuple類型,kwargs是可選參數。
線程的結束可以等待線程自然結束,也可以在線程函數中調用thread.exit()或者thread.exit_thread()方法
(2)創(chuàng)建Threading.thread的子類來包裝一個線程對象 ,如下例:
#coding:utf-8
#使用threading.Thread的子類來包裝一個線程對象
import threading
import time
class timer(threading.Thread): #timer類繼承于threading.Tread
def __init__(self,num,interval):
threading.Thread.__init__(self)
self.thread_num=num
self.interval=interval
self.thread_stop=False
def run(self):
while not self.thread_stop:
print 'Thread Object(%d),Time:%s'%(self.thread_num,time.ctime())
time.sleep(self.interval)
def stop(self):
self.thread_stop=True
def test(self):
thread1=timer(1,1)
thread2 = timer(2, 2)
thread1.start()
thread2.start()
time.sleep(10)
thread1.stop()
thread2.stop()
return第二種方式,即創(chuàng)建自己的線程類,必要時可以重寫threading.Thread類的方法,線程的控制可以由自己定制。
threading.Thread類的使用:
1、在自己的線程類的__init__里調用threading.Thread.__init__(self, name = threadname)
Threadname為線程的名字
2、run(),通常需要重寫,編寫代碼實現做需要的功能。
3、getName(),獲得線程對象名稱
4、setName(),設置線程對象名稱
5、start(),啟動線程
6、jion([timeout]),等待另一線程結束后再運行。
7、setDaemon(bool),設置子線程是否隨主線程一起結束,必須在start()之前調用。默認為False。
8、isDaemon(),判斷線程是否隨主線程一起結束。
9、isAlive(),檢查線程是否在運行中。
到此這篇關于關于Python的Thread線程模塊詳解的文章就介紹到這了,更多相關Python的Thread線程模塊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
將Python代碼打包成可調用SDK的四種方法小結(適用于移動端 App)
Python是一門功能強大、生態(tài)豐富的語言,廣泛用于數據處理、機器學習和后端服務,然而,Python并不是原生的移動端開發(fā)語言,如果希望在移動端App中調用Python代碼,最好的方式是將Python代碼打包成SDK,所以本文給大家介紹了幾種Python代碼打包成可調用SDK的方法2025-04-04

