python實(shí)現(xiàn)多線程的方法

這篇文章將為大家詳細(xì)講解有關(guān)python實(shí)現(xiàn)多線程的方法,小編覺得挺實(shí)用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

創(chuàng)新互聯(lián)公司技術(shù)團(tuán)隊(duì)十余年來致力于為客戶提供網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)、高端網(wǎng)站設(shè)計(jì)全網(wǎng)營銷推廣、搜索引擎SEO優(yōu)化等服務(wù)。經(jīng)過多年發(fā)展,公司擁有經(jīng)驗(yàn)豐富的技術(shù)團(tuán)隊(duì),先后服務(wù)、推廣了成百上千網(wǎng)站,包括各類中小企業(yè)、企事單位、高校等機(jī)構(gòu)單位。

python實(shí)現(xiàn)多線程的方法:

1、Thread直接創(chuàng)建子線程

首先可以使用 Thread 類來創(chuàng)建一個線程,創(chuàng)建時(shí)需要指定 target 參數(shù)為運(yùn)行的方法名稱,如果被調(diào)用的方法需要傳入額外的參數(shù),則可以通過 Thread 的 args 參數(shù)來指定。

import threading
import time
def target(second):
    print(f'Threading {threading.current_thread().name} is running')
    print(f'Threading {threading.current_thread().name} sleep {second}s')
    time.sleep(second)
    print(f'Threading {threading.current_thread().name} is ended')
print(f'Threading {threading.current_thread().name} is running')
for i in [1, 5]:
    thread = threading.Thread(target=target, args=[i])
    thread.start()
    
print(f'Threading {threading.current_thread().name} is ended')

運(yùn)行結(jié)果:

Threading MainThread is running
Threading Thread-1 is running
Threading Thread-1 sleep 1s
Threading Thread-2 is running
Threading Thread-2 sleep 5s
Threading MainThread is ended
Threading Thread-1 is ended
Threading Thread-2 is ended

如果想要主線程等待子線程運(yùn)行完畢之后才退出,可以讓每個子線程對象都調(diào)用下 join 方法:

threads = []
for i in [1, 5]:
    thread = threading.Thread(target=target, args=[i])
    threads.append(thread)
    thread.start()
    
for thread in threads:
    thread.join()

運(yùn)行結(jié)果:

Threading MainThread is running
Threading Thread-1 is running
Threading Thread-1 sleep 1s
Threading Thread-2 is running
Threading Thread-2 sleep 5s
Threading Thread-1 is ended
Threading Thread-2 is ended
Threading MainThread is ended

2、繼承Thread類創(chuàng)建子線程

另外也可以通過繼承 Thread 類的方式創(chuàng)建一個線程,該線程需要執(zhí)行的方法寫在類的 run 方法里面即可。上面的例子的等價(jià)改寫為:

import threading
import time
class MyThread(threading.Thread):
    def __init__(self, second):
        threading.Thread.__init__(self)
        self.second = second
    
    def run(self):
        print(f'Threading {threading.current_thread().name} is running')
        print(f'Threading {threading.current_thread().name} sleep {self.second}s')
        time.sleep(self.second)
        print(f'Threading {threading.current_thread().name} is ended')
print(f'Threading {threading.current_thread().name} is running')
threads = []
for i in [1, 5]:
    thread = MyThread(i)
    threads.append(thread)
    thread.start()
    
for thread in threads:
    thread.join()
    
print(f'Threading {threading.current_thread().name} is ended')

運(yùn)行結(jié)果:

Threading MainThread is running
Threading Thread-1 is running 
Threading Thread-1 sleep 1s 
Threading Thread-2 is running 
Threading Thread-2 sleep 5s 
Threading Thread-1 is ended 
Threading Thread-2 is ended 
Threading MainThread is ended

守護(hù)線程

在線程中有一個叫作守護(hù)線程的概念,如果一個線程被設(shè)置為守護(hù)線程,那么意味著這個線程是“不重要”的,這意味著,如果主線程結(jié)束了而該守護(hù)線程還沒有運(yùn)行完,那么它將會被強(qiáng)制結(jié)束。

在 Python 中我們可以通過 setDaemon 方法來將某個線程設(shè)置為守護(hù)線程:

import threading
import time
def target(second):
    print(f'Threading {threading.current_thread().name} is running')
    print(f'Threading {threading.current_thread().name} sleep {second}s')
    time.sleep(second)
    print(f'Threading {threading.current_thread().name} is ended')
print(f'Threading {threading.current_thread().name} is running')
t1 = threading.Thread(target=target, args=[2])
t1.start()
t2 = threading.Thread(target=target, args=[5])
t2.setDaemon(True)
t2.start()
print(f'Threading {threading.current_thread().name} is ended')

運(yùn)行結(jié)果:

Threading MainThread is running 
Threading Thread-1 is running 
Threading Thread-1 sleep 2s 
Threading Thread-2 is running 
Threading Thread-2 sleep 5s 
Threading MainThread is ended 
Threading Thread-1 is ended

互斥鎖

在一個進(jìn)程中的多個線程是共享資源的,比如在一個進(jìn)程中,有一個全局變量 count 用來計(jì)數(shù),現(xiàn)在聲明多個線程,每個線程運(yùn)行時(shí)都給 count 加 1,代碼實(shí)現(xiàn)如下:

import threading
import time
count = 0
class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global count
        temp = count + 1
        time.sleep(0.001)
        count = temp
threads = []
for _ in range(1000):
    thread = MyThread()
    thread.start()
    threads.append(thread)
for thread in threads:
    thread.join()
    
print(f'Final count: {count}')

運(yùn)行結(jié)果:

Final count: 69

由于 count 這個值是共享的,每個線程都可以在執(zhí)行 temp = count 這行代碼時(shí)拿到當(dāng)前 count 的值,但是這些線程中的一些線程可能是并發(fā)或者并行執(zhí)行的,這就導(dǎo)致不同的線程拿到的可能是同一個 count 值,最后導(dǎo)致有些線程的 count 的加 1 操作并沒有生效,導(dǎo)致最后的結(jié)果偏小。

所以,如果多個線程同時(shí)對某個數(shù)據(jù)進(jìn)行讀取或修改,就會出現(xiàn)不可預(yù)料的結(jié)果。為了避免這種情況,我們需要對多個線程進(jìn)行同步,要實(shí)現(xiàn)同步,我們可以對需要操作的數(shù)據(jù)進(jìn)行加鎖保護(hù),這里就需要用到 threading.Lock 了。

加鎖保護(hù)

某個線程在對數(shù)據(jù)進(jìn)行操作前,需要先加鎖,這樣其他的線程發(fā)現(xiàn)被加鎖了之后,就無法繼續(xù)向下執(zhí)行,會一直等待鎖被釋放,只有加鎖的線程把鎖釋放了,其他的線程才能繼續(xù)加鎖并對數(shù)據(jù)做修改,修改完了再釋放鎖。

這樣可以確保同一時(shí)間只有一個線程操作數(shù)據(jù),多個線程不會再同時(shí)讀取和修改同一個數(shù)據(jù)。

關(guān)于python實(shí)現(xiàn)多線程的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

文章名稱:python實(shí)現(xiàn)多線程的方法
文章分享:http://bm7419.com/article36/jcsdsg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊、Google移動網(wǎng)站建設(shè)、營銷型網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、網(wǎng)站收錄

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)