欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于Python的Thread線程模塊詳解

 更新時(shí)間:2023年05月18日 09:23:10   作者:FLy_鵬程萬里  
這篇文章主要介紹了關(guān)于Python的Thread線程模塊詳解,進(jìn)程是程序的一次執(zhí)行,每個(gè)進(jìn)程都有自己的地址空間、內(nèi)存、數(shù)據(jù)棧以及其他記錄其運(yùn)行的輔助數(shù)據(jù),需要的朋友可以參考下

Python線程與進(jìn)程

進(jìn)程:進(jìn)程是程序的一次執(zhí)行,每個(gè)進(jìn)程都有自己的地址空間、內(nèi)存、數(shù)據(jù)棧以及其他記錄其運(yùn)行的輔助數(shù)據(jù)。

線程:所有的線程運(yùn)行在同一個(gè)進(jìn)程中,共享相同的運(yùn)行環(huán)境。線程有開始順序執(zhí)行和結(jié)束三個(gè)部分。

舉例說明:

(1)計(jì)算機(jī)的核心是CPU,它承擔(dān)了所有的計(jì)算任務(wù),它就像一座工廠,時(shí)刻在運(yùn)行。

(2)假定工廠的電力有限,一次只能供給一個(gè)車間使用,也就是說,一個(gè)車間開工的時(shí)候,其他工廠度必須要停下來。其背后的意思就是,單個(gè)CPU一次只能運(yùn)行一個(gè)任務(wù)。

(3)進(jìn)程就好比工廠的車間,它代表CPU所能處理的單個(gè)任務(wù),任意時(shí)刻,CPU總是運(yùn)行一個(gè)進(jìn)程,其他進(jìn)程處于非運(yùn)行狀態(tài)。

(4)一個(gè)車間里,可以有很多工人,他們協(xié)同完成一個(gè)任務(wù)。

(5)線程就好比車間里的工人,一個(gè)進(jìn)程可以包括多個(gè)線程。

Python thread模塊

python threading模塊

python中線程的使用

python中使用線程的方法有兩種:函數(shù)、通過類來包裝線程對(duì)象

(1)函數(shù)式:調(diào)用thread模塊中的start_new_thread()函數(shù)來產(chǎn)生新的線程。如下例:

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])的第一個(gè)參數(shù)時(shí)線程函數(shù),第二個(gè)參數(shù)時(shí)傳遞給線程函數(shù)的參數(shù),它必須是tuple類型,kwargs是可選參數(shù)。

線程的結(jié)束可以等待線程自然結(jié)束,也可以在線程函數(shù)中調(diào)用thread.exit()或者thread.exit_thread()方法

(2)創(chuàng)建Threading.thread的子類來包裝一個(gè)線程對(duì)象 ,如下例:

#coding:utf-8
#使用threading.Thread的子類來包裝一個(gè)線程對(duì)象
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)建自己的線程類,必要時(shí)可以重寫threading.Thread類的方法,線程的控制可以由自己定制。

 threading.Thread類的使用: 

1、在自己的線程類的__init__里調(diào)用threading.Thread.__init__(self, name = threadname) 
Threadname為線程的名字 
2、run(),通常需要重寫,編寫代碼實(shí)現(xiàn)做需要的功能。 
3、getName(),獲得線程對(duì)象名稱 
4、setName(),設(shè)置線程對(duì)象名稱 
5、start(),啟動(dòng)線程 
6、jion([timeout]),等待另一線程結(jié)束后再運(yùn)行。 
7、setDaemon(bool),設(shè)置子線程是否隨主線程一起結(jié)束,必須在start()之前調(diào)用。默認(rèn)為False。 
8、isDaemon(),判斷線程是否隨主線程一起結(jié)束。 
9、isAlive(),檢查線程是否在運(yùn)行中。 

到此這篇關(guān)于關(guān)于Python的Thread線程模塊詳解的文章就介紹到這了,更多相關(guān)Python的Thread線程模塊內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論