在线观看www成人影院-在线观看www日本免费网站-在线观看www视频-在线观看操-欧美18在线-欧美1级

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

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

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

Python3多線程核心知識

馬哥Linux運(yùn)維 ? 來源:未知 ? 作者:李倩 ? 2018-04-16 11:46 ? 次閱讀

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

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

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

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

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

線程可以分為:

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

用戶線程:不需要內(nèi)核支持而在用戶程序中實(shí)現(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

# 返回當(dāng)前時間的時間戳(1970紀(jì)元后經(jīng)過的浮點(diǎn)秒數(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(): 返回當(dāng)前的線程變量。

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

threading.activeCount(): 返回正在運(yùn)行的線程數(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)建進(jìn)程類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)勢在于可以同時運(yùn)行多個任務(wù)(至少感覺起來是這樣)。但是當(dāng)線程需要共享數(shù)據(jù)時,可能存在數(shù)據(jù)不同步的問題。

使用 Thread 對象的 Lock 和 Rlock 可以實(shí)現(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。

這些隊列都實(shí)現(xiàn)了鎖原語,能夠在多線程中直接使用,可以使用隊列來實(shí)現(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() 相當(dāng)Queue.get(False)

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

Queue.put_nowait(item) 相當(dāng)Queue.put(item, False)

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

Queue.join() 實(shí)際上意味著等到隊列為空,再執(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

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

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

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

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

    關(guān)注

    31

    文章

    5425

    瀏覽量

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

    關(guān)注

    68

    文章

    11051

    瀏覽量

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

    關(guān)注

    0

    文章

    507

    瀏覽量

    20109

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

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

收藏 人收藏

    評論

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

    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

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

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

    一種實(shí)時多線程VSLAM框架vS-Graphs介紹

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

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

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

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

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

    使用Yolo-v3-TF運(yùn)行OpenVINO?對象檢測Python演示時的結(jié)果不準(zhǔn)確的原因?

    通過模型下載器下載了 yolo-v3-tf: ./downloader.py --name yolo-v3-tf 通過模型 優(yōu)化器轉(zhuǎn)換模型: python3 ./model_optimizer
    發(fā)表于 03-06 06:31

    請問rt-thread studio如何進(jìn)行多線程編譯?

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

    掌握EMC核心知識——7天倒計時!

    賽盛技術(shù)第九期“EMC實(shí)戰(zhàn)特訓(xùn)營“開課倒計時7天”!本期課特訓(xùn)營將于12月18日正式開課,課程涵蓋電磁兼容(EMC)領(lǐng)域的核心知識。四位資深講師主講,團(tuán)隊經(jīng)驗(yàn)累計超過70年,并結(jié)合賽盛技術(shù)公司19年
    的頭像 發(fā)表于 12-11 09:40 ?515次閱讀
    掌握EMC<b class='flag-5'>核心知識</b>——7天倒計時!

    socket 多線程編程實(shí)現(xiàn)方法

    在現(xiàn)代網(wǎng)絡(luò)編程中,多線程技術(shù)被廣泛應(yīng)用于提高服務(wù)器的并發(fā)處理能力。Socket編程是網(wǎng)絡(luò)通信的基礎(chǔ),而將多線程技術(shù)應(yīng)用于Socket編程,可以顯著提升服務(wù)器的性能。 多線程編程的基本概念 多線
    的頭像 發(fā)表于 11-12 14:16 ?932次閱讀

    Python多線程和多進(jìn)程的區(qū)別

    Python作為一種高級編程語言,提供了多種并發(fā)編程的方式,其中多線程與多進(jìn)程是最常見的兩種方式之一。在本文中,我們將探討Python多線程與多進(jìn)程的概念、區(qū)別以及如何使用
    的頭像 發(fā)表于 10-23 11:48 ?952次閱讀
    <b class='flag-5'>Python</b>中<b class='flag-5'>多線程</b>和多進(jìn)程的區(qū)別

    迅為3A6000_7A2000核心主板龍芯全國產(chǎn)處理器LoongArch架構(gòu)

    個最新研發(fā)的高性能 LA664 處理器核,支持同時多線程技術(shù)(SMT2),全芯片共 8 個邏輯核。集成安全可信模塊,可提供安全啟動方案和國密(SM2、SM3、SM4 等)應(yīng)用支持。 根據(jù)中國電
    發(fā)表于 10-12 11:25

    一文掌握Python多線程

    使用線程可以把占據(jù)長時間的程序中的任務(wù)放到后臺去處理。
    的頭像 發(fā)表于 08-05 15:46 ?1206次閱讀

    ESP32會不會有多線程問題,需要加鎖嗎?

    ESP32會不會有多線程問題,需要加鎖嗎
    發(fā)表于 07-19 08:05

    【PHYTEC AM62x開發(fā)板試用】準(zhǔn)備工作

    locales lz4 openssh-client pylint python python3 python3-distutils python3-git
    發(fā)表于 07-01 16:22

    多線程設(shè)計模式到對 CompletableFuture 的應(yīng)用

    最近在開發(fā) 延保服務(wù) 頻道頁時,為了提高查詢效率,使用到了多線程技術(shù)。為了對多線程方案設(shè)計有更加充分的了解,在業(yè)余時間讀完了《圖解 Java 多線程設(shè)計模式》這本書,覺得收獲良多。本篇文章將介紹其中
    的頭像 發(fā)表于 06-26 14:18 ?641次閱讀
    從<b class='flag-5'>多線程</b>設(shè)計模式到對 CompletableFuture 的應(yīng)用
    主站蜘蛛池模板: 男女交性动态免费视频 | 亚洲日本欧美日韩高观看 | 天堂资源在线种子资源 | 偷偷要色偷偷 | 四虎永久免费网站入口2020 | ts人妖国产一区 | 色香视频一sxmv首页 | h网站在线观看 | 久久影视免费体验区午夜啪啪 | 在线成人免费观看国产精品 | 黄色理伦| 18黄无遮挡免费视频 | 看屁屁www视频免费观看 | 狠狠干精品| 国产香蕉视频在线播放 | 天天操夜夜添 | 男人视频网 | 日韩成人在线影院 | 日日夜夜狠狠 | 成年人电影黄色 | 无内丝袜透明在线播放 | 国产成人悠悠影院 | 男男扒开后菊惩罚 | www.四虎影院在线观看 | 欧美3d动漫网站 | 天天天综合网 | 久久黄网站 | 91成人午夜性a一级毛片 | 老色批影院 | а8天堂资源在线官网 | 在线播放一区二区精品产 | 色老头在线精品视频在线播放 | 男人的天堂免费网站 | 国产色视频网站 | 色综合一区二区三区 | 韩国韩宝贝2020vip福利视频 | 美女教师一级毛片 | 日韩毛片在线视频 | 精品一区二区视频 | 国产成人永久在线播放 | 国产美女在线精品免费观看 |