91欧美超碰AV自拍|国产成年人性爱视频免费看|亚洲 日韩 欧美一厂二区入|人人看人人爽人人操aV|丝袜美腿视频一区二区在线看|人人操人人爽人人爱|婷婷五月天超碰|97色色欧美亚州A√|另类A√无码精品一级av|欧美特级日韩特级

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

Python3多線程核心知識

馬哥Linux運維 ? 來源:未知 ? 作者:李倩 ? 2018-04-16 11:46 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

每個獨立的線程有一個程序運行的入口、順序執(zhí)行序列和程序的出口。但是線程不能夠獨立執(zhí)行,必須依存在應(yīng)用程序中,由應(yīng)用程序提供多個線程執(zhí)行控制。

每個線程都有他自己的一組CPU寄存器,稱為線程的上下文,該上下文反映了線程上次運行該線程的CPU寄存器的狀態(tài)。

指令指針和堆棧指針寄存器是線程上下文中兩個最重要的寄存器,線程總是在進程得到上下文中運行的,這些地址都用于標志擁有線程的進程地址空間中的內(nèi)存。

線程可以被搶占(中斷)。

在其他線程正在運行時,線程可以暫時擱置(也稱為睡眠) -- 這就是線程的退讓。

線程可以分為:

內(nèi)核線程:由操作系統(tǒng)內(nèi)核創(chuàng)建和撤銷。

用戶線程:不需要內(nèi)核支持而在用戶程序中實現(xiàn)的線程。

Python3 線程中常用的兩個模塊為:

_thread

threading(推薦使用)

函數(shù)式

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

_thread.start_new_thread ( function, args[, kwargs] )

參數(shù)說明:

function - 線程函數(shù)。

args - 傳遞給線程函數(shù)的參數(shù),他必須是個tuple類型。

kwargs - 可選參數(shù)。

import _thread, time# 定義線程函數(shù)def print_time(threadName, delay):

count = 0 while count < 5: ? ?

time.sleep(delay)

count += 1

# 返回當前時間的時間戳(1970紀元后經(jīng)過的浮點秒數(shù)), 并格式化輸出

print("{}: {}".format(threadName, time.ctime(time.time()) ))try:

_thread.start_new_thread( print_time, ("Thread-1", 2))

_thread.start_new_thread( print_time, ("Thread-2", 4))except:

print("Error")while 1: # 讓線程有足夠的時間完成 pass

E:\PyPro>python thread.pyThread-1: Thu Apr 12 09:01:56 2018Thread-2: Thu Apr 12 09:01:58 2018Thread-1: Thu Apr 12 09:01:58 2018Thread-1: Thu Apr 12 09:02:00 2018Thread-2: Thu Apr 12 09:02:02 2018Thread-1: Thu Apr 12 09:02:02 2018Thread-1: Thu Apr 12 09:02:05 2018Thread-2: Thu Apr 12 09:02:06 2018Thread-2: Thu Apr 12 09:02:10 2018Thread-2: Thu Apr 12 09:02:14 2018

類封裝式

threading 模塊除了包含 _thread 模塊中的所有方法外,還提供的其他方法:

threading.currentThread(): 返回當前的線程變量。

threading.enumerate(): 返回一個包含正在運行的線程的list。正在運行指線程啟動后、結(jié)束前,不包括啟動前和終止后的線程。

threading.activeCount(): 返回正在運行的線程數(shù)量,與len(threading.enumerate())有相同的結(jié)果。

線程模塊同樣提供了Thread類來處理線程,Thread類提供了以下方法:

run():用以表示線程活動的方法。

start():啟動線程活動。

join([time]):等待至線程中止。這阻塞調(diào)用線程直至線程的join() 方法被調(diào)用中止-正常退出或者拋出未處理的異常-或者是可選的超時發(fā)生。

isAlive():返回線程是否活動的。

getName():返回線程名。

setName():設(shè)置線程名。

import threading, time# 創(chuàng)建進程類class myThread(threading.Thread):

# 構(gòu)造函數(shù) def __init__(self, threadID, name, counter):

threading.Thread.__init__(self)

self.threadID = threadID

self.name = name

self.counter = counter

# 重寫run()

def run(self):

print("Thread Strat:" + self.name)

print_time(self.name, self.counter, 5)

print("Thread Exit:" + self.name)

def print_time(threadName, delay, counter):

while counter:

time.sleep(delay)

print("{}: {}".format(threadName, time.ctime(time.time()) ))

counter -= 1

# 創(chuàng)建線程thread1 = myThread(1001, "Thread-1", 1)thread2 = myThread(1002, "Thread-2", 2)# 開啟線程print("Thread-1 is Alive? ", thread1.isAlive())thread1.start()thread2.start()print("Thread-1 is Alive? ", thread1.isAlive())thread1.join()thread2.join()print("Thread-1 is Alive? ", thread1.isAlive())print("exit")

E:\PyPro>python threadClass.pyThread-1 is Alive? FalseThread Strat:

Thread-1Thread Strat:

Thread-2Thread-1 is Alive? TrueThread-1: Thu Apr 12 10:15:53 2018Thread-1:

Thu Apr 12 10:15:54 2018Thread-2: Thu Apr 12 10:15:54 2018Thread-1: Thu Apr 12 10:15:55 2018Thread-1:

Thu Apr 12 10:15:56 2018Thread-2: Thu Apr 12 10:15:56 2018Thread-1: Thu Apr 12 10:15:57 2018Thread Exit:

Thread-1Thread-2: Thu Apr 12 10:15:58 2018Thread-2: Thu Apr 12 10:16:00 2018Thread-2: Thu Apr 12 10:16:02 2018Thread Exit:

Thread-2Thread-1 is Alive? Falseexit

不難發(fā)現(xiàn),線程是通過start()函數(shù)激活,而不是對象建立時激活的!

線程同步

多線程的優(yōu)勢在于可以同時運行多個任務(wù)(至少感覺起來是這樣)。但是當線程需要共享數(shù)據(jù)時,可能存在數(shù)據(jù)不同步的問題。

使用 Thread 對象的 Lock 和 Rlock 可以實現(xiàn)簡單的線程同步,這兩個對象都有 acquire 方法和 release 方法,對于那些需要每次只允許一個線程操作的數(shù)據(jù),可以將其操作放到 acquire 和 release 方法之間。

import threading, time# 創(chuàng)建鎖threadLock = threading.Lock()# 創(chuàng)建線程列表threads = []class myThread(threading.Thread):

def __init__(self, threadID, name, counter):

threading.Thread.__init__(self)

self.threadID = threadID

self.name = name

self.counter = counter

def run(self):

print("Thread Start: " + self.name)

# 獲取鎖,同步線程

threadLock.acquire()

print_time(self.name, self.counter, 3)

# 釋放鎖,開啟下一個線程

threadLock.release()

print("Thread Exit: " + self.name)

def print_time(threadName, delay, counter):

while counter:

time.sleep(delay)

print("{}: {}".format(threadName, time.ctime()))

counter -= 1

# 創(chuàng)建線程thread1 = myThread(1001, "Thread-1", 1)thread2 = myThread(1002, "Thread-2", 2)# 開啟線程thread1.start()thread2.start()# 添加線程列表threads.append(thread1)threads.append(thread2)# 等待所有線程完成for t in threads: t.join()print("exit")

E:\PyPro>python synchronize.pyThread Start: Thread-1Thread Start: Thread-2Thread-1: Thu Apr 12 11:00:49 2018Thread-1: Thu Apr 12 11:00:50 2018Thread-1: Thu Apr 12 11:00:51 2018Thread Exit: Thread-1Thread-2: Thu Apr 12 11:00:53 2018Thread-2: Thu Apr 12 11:00:55 2018Thread-2: Thu Apr 12 11:00:57 2018Thread Exit: Thread-2exit

線程優(yōu)先級隊列

Python 的 Queue 模塊中提供了同步的、線程安全的隊列類,包括FIFO隊列Queue,LIFO隊列LifoQueue,和優(yōu)先級隊列 PriorityQueue。

這些隊列都實現(xiàn)了鎖原語,能夠在多線程中直接使用,可以使用隊列來實現(xiàn)線程間的同步。

Queue 模塊中的常用方法:

Queue.qsize() 返回隊列的大小

Queue.empty() 如果隊列為空,返回True,反之False

Queue.full() 如果隊列滿了,返回True,反之False

Queue.full 與 maxsize 大小對應(yīng)

Queue.get([block[, timeout]])獲取隊列,timeout等待時間

Queue.get_nowait() 相當Queue.get(False)

Queue.put(item) 寫入隊列,timeout等待時間

Queue.put_nowait(item) 相當Queue.put(item, False)

Queue.task_done() 在完成一項工作之后,Queue.task_done()函數(shù)向任務(wù)已經(jīng)完成的隊列發(fā)送一個信號

Queue.join() 實際上意味著等到隊列為空,再執(zhí)行別的操作

import queue, threading, timeexitFlag = 0# 創(chuàng)建鎖queueLock = threading.Lock()# 創(chuàng)建隊列workQueue = queue.Queue(10)class myThread(threading.Thread):

def __init__(self, threadID, name, q):

threading.Thread.__init__(self)

self.threadID = threadID

self.name = name

self.q = q

def run(self):

print("Thread Start: " + self.name)

process_data(self.name, self.q)

print("Thread Exit: " + self.name)

def process_data(threadName, q):

while not exitFlag:

queueLock.acquire()

if not workQueue.empty():

data = q.get()

queueLock.release()

print("{} processing {}".format(threadName, data))

else:

queueLock.release()

time.sleep(1)threadList = ["Thread-1", "Thread-2", "Thread-3"]nameList = ["One", "Two", "Three", "Four", "Five"]threads = []threadID = 1# 創(chuàng)建新線程for tName in threadList:

thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread)

threadID += 1# 填充隊列queueLock.acquire()print

("隊列填充中>>>>>>>>>>>>>>")time.sleep(1)for word in nameList: workQueue.put(word)print("隊列填充完畢>>>>>>>>>>>>>>")queueLock.release()# 等待隊列清空while not workQueue.empty(): pass# 通知線程退出exitFlag = 1# 等待所有線程完成for t in threads: t.join()print("exit")

E:\PyPro>python queueue.pyThread Start: Thread-1Thread Start: Thread-2Thread Start: Thread-3隊列填充中>>>>>>>>>>>>>>隊列填充完畢>>>>>>>>>>>>>>Thread-3 processing OneThread-1 processing TwoThread-2 processing ThreeThread-3 processing FourThread-1 processing FiveThread Exit: Thread-2Thread Exit: Thread-1Thread Exit: Thread-3exit

源碼中其實實現(xiàn)了三個進程讀取同一個隊列,按照先進先出原則實現(xiàn)鎖定。

用start方法來啟動線程,真正實現(xiàn)了多線程運行,這時無需等待run方法體代碼執(zhí)行完畢而直接繼續(xù)執(zhí)行下面的代碼。通過調(diào)用Thread類的start()方法來啟動一個線程,這時此線程處于就緒(可運行)狀態(tài),并沒有運行,一旦得到cpu時間片,就開始執(zhí)行run()方法,這里方法 run()稱為線程體,它包含了要執(zhí)行的這個線程的內(nèi)容,Run方法運行結(jié)束,此線程隨即終止。

join的作用是保證當前線程執(zhí)行完成后,再執(zhí)行其它線程。join可以有timeout參數(shù),表示阻塞其它線程timeout秒后,不再阻塞。。一般線程的start()之后,所有操作結(jié)束后都要進行thread.join()。確保語句的輸出是join()后面的程序是等線程結(jié)束后再執(zhí)行的。

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學習之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 寄存器
    +關(guān)注

    關(guān)注

    31

    文章

    5609

    瀏覽量

    130016
  • cpu
    cpu
    +關(guān)注

    關(guān)注

    68

    文章

    11281

    瀏覽量

    225098
  • 線程
    +關(guān)注

    關(guān)注

    0

    文章

    509

    瀏覽量

    20829

原文標題:十分鐘帶你了解 Python3 多線程核心知識

文章出處:【微信號:magedu-Linux,微信公眾號:馬哥Linux運維】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。

收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評論

    相關(guān)推薦
    熱點推薦

    安裝 Python VisionFive_GPIO失敗是哪里出了問題?

    盡管按照最新的文檔,我在安裝 VisionFive.gpio 包時仍然收到錯誤 sudo apt 安裝 libxml2-dev libxslt-dev python3 -m pip 安裝請求
    發(fā)表于 02-11 06:13

    【瑞薩RA × Zephyr評測】多線程和看門狗

    本文章旨在評估使用 Zephyr RTOS 在 Renesas FPB-RA6E2 開發(fā)板上實現(xiàn)多線程調(diào)度與硬件看門狗功能的應(yīng)用。評估內(nèi)容包括任務(wù)調(diào)度、看門狗初始化流程、主程序邏輯的詳細解析,以及實驗現(xiàn)象與數(shù)據(jù)分析。
    的頭像 發(fā)表于 01-10 10:23 ?2481次閱讀
    【瑞薩RA × Zephyr評測】<b class='flag-5'>多線程</b>和看門狗

    三防漆知識百科:三防漆是什么?核心價值有哪些?

    、航空航天等18大行業(yè),2024年國內(nèi)市場規(guī)模已突破48億元,其中汽車電子、工業(yè)控制領(lǐng)域需求同比激增32%。本文以知識百科形式,全面拆解三防漆的核心知識點,助力行
    的頭像 發(fā)表于 12-27 17:38 ?537次閱讀
    三防漆<b class='flag-5'>知識</b>百科:三防漆是什么?<b class='flag-5'>核心</b>價值有哪些?

    解析Linux的進程、線程和協(xié)程

    和系統(tǒng)資源。線程的引入使得多核處理器得以充分利用,因為多線程程序可以更有效地分配和管理多核心的計算資源。 線程的特點包括: (1)共享性:線程
    發(fā)表于 12-22 11:00

    多線程的系統(tǒng)

    ) { /* 無限循環(huán),不能返回 */ for (;;) { /* 線程實體 */ if (flag3) { } } } 相比前后臺系統(tǒng)中后臺順序執(zhí)行的程序主體,在多線程系統(tǒng)中,根據(jù)程序的功能
    發(fā)表于 12-08 07:55

    Linux多線程對比單線程的優(yōu)勢

    :「資源利用率」:通過多線程,可以更有效地利用CPU資源,特別是多核CPU?!覆⑿刑幚怼梗?b class='flag-5'>線程允許同時執(zhí)行多個任務(wù),提高程序的執(zhí)行效率?!负喕O(shè)計」:使用線程可以簡化程序設(shè)計,因為線程
    發(fā)表于 12-01 06:11

    【CIE全國RISC-V創(chuàng)新應(yīng)用大賽】MUSE PI PRO 測評

    if=/dev/zero of=/mnt/usb/test.bin bs=1M count=10 Python環(huán)境:python3 --version(3.10剛好支持YOLO)→pip3
    發(fā)表于 11-28 19:00

    rt-thread studio 如何進行多線程編譯?

    ,使用的是5800h+32g內(nèi)存+sn550 ssd,開啟16線程編譯時cpu的占用率也只能到30%,編譯完整個工程需要3分鐘 感覺多線程編譯設(shè)置沒有生效,有辦法提高編譯速度嗎 rtthread studio版本是 2.2.9
    發(fā)表于 10-11 09:16

    【HZ-T536開發(fā)板免費體驗】—— linux創(chuàng)建線程

    自己的私有資源。 在linux系統(tǒng)中,線程狀態(tài)通常反映了當前線程的當前活動和執(zhí)行階段。 主要分為: 1。運行轉(zhuǎn)態(tài) 2。阻塞轉(zhuǎn)態(tài) 3。終止狀態(tài) 如何區(qū)分單線程
    發(fā)表于 09-01 21:31

    多線程的安全注意事項

    多線程安全是指多個線程同時訪問或修改共享資源時,能夠保證程序的正確性和可靠性。 開發(fā)者選擇TaskPool或Worker進行多線程開發(fā)時,在TaskPool和Worker的工作線程中導(dǎo)
    發(fā)表于 06-20 07:49

    Hi3861 wifiiot_hispark_pegasus 按教程安裝python3 -m pip install build/lite 報錯

    問題1: 報錯: 問題2: 我安裝網(wǎng)上搜的方法執(zhí)行 python3 -m pip install --user ohos-build==0.4.3 hb -v [OHOS INFO] hb
    發(fā)表于 06-14 16:48

    工控一體機多線程任務(wù)調(diào)度優(yōu)化:聚徽分享破解工業(yè)復(fù)雜流程高效協(xié)同密碼

    在當今工業(yè) 4.0 的浪潮下,工業(yè)生產(chǎn)正朝著高度自動化、智能化的方向大步邁進。生產(chǎn)流程日益復(fù)雜,眾多任務(wù)需要同時、高效地協(xié)同執(zhí)行,這對工業(yè)控制系統(tǒng)的核心 —— 工控一體機提出了前所未有的挑戰(zhàn)。多線程
    的頭像 發(fā)表于 05-28 14:06 ?640次閱讀

    一種實時多線程VSLAM框架vS-Graphs介紹

    針對現(xiàn)有VSLAM系統(tǒng)語義表達不足、地圖可解釋性差的問題,本文提出vS-Graphs,一種實時多線程VSLAM框架。該方案顯著提升了重建地圖的語義豐富度、可解釋性及定位精度。實驗表明
    的頭像 發(fā)表于 04-19 14:07 ?1014次閱讀
    一種實時<b class='flag-5'>多線程</b>VSLAM框架vS-Graphs介紹

    ?如何在虛擬環(huán)境中使用 Python,提升你的開發(fā)體驗~

    。RaspberryPiOS預(yù)裝了Python3。干擾系統(tǒng)Python的安裝可能會給你的操作系統(tǒng)帶來問題。安裝第三方Python庫時,請務(wù)必使用正確的包管理工具。在Lin
    的頭像 發(fā)表于 03-25 09:34 ?818次閱讀
    ?如何在虛擬環(huán)境中使用 <b class='flag-5'>Python</b>,提升你的開發(fā)體驗~

    請問如何在Python中實現(xiàn)多線程與多進程的協(xié)作?

    大家好!我最近在開發(fā)一個Python項目時,需要同時處理多個任務(wù),且每個任務(wù)需要不同的計算資源。我想通過多線程和多進程的組合來實現(xiàn)并發(fā),但遇到了一些問題。 具體來說,我有兩個任務(wù),一個是I/O密集型
    發(fā)表于 03-11 06:57