自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python 多線程編程的十個(gè)關(guān)鍵概念

開發(fā)
今天我們要一起探索的是Python編程中的一個(gè)超炫酷領(lǐng)域——多線程,希望能對(duì)Python多線程有更深入的理解。

今天我們要一起探索的是Python編程中的一個(gè)超炫酷領(lǐng)域——多線程!想象一下,你的程序能像超人一樣同時(shí)處理多個(gè)任務(wù),是不是很激動(dòng)人心?讓我們以輕松愉快的方式,一步步揭開它的神秘面紗。

1. 線程的初步認(rèn)知

想象你是個(gè)廚房大廚,一邊炒菜一邊洗菜,這就是多線程的日常。在Python里,threading模塊就是我們的廚房神器。

import threading

def cook():  # 炒菜線程
    print("炒菜中...")
    
def wash():  # 洗菜線程
    print("洗菜中...")

# 創(chuàng)建線程對(duì)象
thread1 = threading.Thread(target=cook)
thread2 = threading.Thread(target=wash)

# 啟動(dòng)線程
thread1.start()
thread2.start()

# 等待所有線程完成
thread1.join()
thread2.join()

print("飯做好啦!")

這段代碼中,Thread類用來創(chuàng)建線程,target參數(shù)指定線程要執(zhí)行的函數(shù)。start()讓線程開始執(zhí)行,而join()確保主線程等待這些小線程們完成它們的任務(wù)。

2. 線程同步:避免廚房混亂

在多線程世界,如果兩個(gè)線程同時(shí)操作同一資源(比如共享食材),就可能出亂子。這時(shí)就需要“鎖”來幫忙了,Python里的鎖叫Lock。

import threading

shared_resource = 0
lock = threading.Lock()

def increase(): 
    global shared_resource
    lock.acquire()  # 上鎖,防止同時(shí)訪問
    shared_resource += 1
    lock.release()  # 解鎖,釋放控制權(quán)

threads = [threading.Thread(target=increase) for _ in range(100)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print("共享資源的最終值:", shared_resource)

每次訪問共享資源前,先acquire()上鎖,操作完后release()解鎖,這樣就避免了數(shù)據(jù)混亂。

3. 死鎖:可怕的廚房僵局

但鎖用不好也會(huì)出問題,就像兩個(gè)廚師互相等待對(duì)方手中的鍋,形成了死鎖。要小心設(shè)計(jì),避免循環(huán)等待。

4. 線程池:高效管理廚房幫手

想象一下,如果你每次炒菜都要新雇一個(gè)廚師,那得多浪費(fèi)?線程池(ThreadPoolExecutor)就是解決這個(gè)問題的神器,它預(yù)先創(chuàng)建好一些線程,重復(fù)利用。

from concurrent.futures import ThreadPoolExecutor

def task(n):
    print(f"執(zhí)行任務(wù){(diào)n}")

with ThreadPoolExecutor(max_workers=5) as executor:
    executor.map(task, range(1, 6))

這里,ThreadPoolExecutor創(chuàng)建了一個(gè)最多有5個(gè)線程的池,map()函數(shù)并行執(zhí)行任務(wù)列表中的每個(gè)任務(wù)。

5. 守護(hù)線程:廚房的清潔工

守護(hù)線程就像廚房的清潔工,在所有其他線程完成后默默清理。通過setDaemon(True)設(shè)置線程為守護(hù)線程。

def cleaner():
    while True:  # 假設(shè)這是一個(gè)無限循環(huán),清理任務(wù)
        print("打掃廚房...")
        if not other_threads_running():  # 假定函數(shù)檢查其他線程是否還在運(yùn)行
            break

clean_thread = threading.Thread(target=cleaner)
clean_thread.setDaemon(True)
clean_thread.start()

# 其他線程的代碼...

print("廚房關(guān)閉,清潔完成。")

6. 線程優(yōu)先級(jí):誰先炒誰先洗

雖然Python標(biāo)準(zhǔn)庫沒有直接提供線程優(yōu)先級(jí)的功能,但可以通過隊(duì)列等間接實(shí)現(xiàn)。不過,大多數(shù)情況下,Python的線程調(diào)度是公平的,不需要擔(dān)心。

7. 全局解釋器鎖(GIL)

Python的GIL是一個(gè)讓人又愛又恨的東西,它保證了任何時(shí)刻只有一個(gè)線程在執(zhí)行Python字節(jié)碼,這對(duì)多核CPU來說不是個(gè)好消息。但在I/O密集型任務(wù)中,GIL的影響沒那么大。

8. 線程局部存儲(chǔ):我的調(diào)料我做主

不同線程需要不同的“調(diào)料”怎么辦?threading.local()來幫忙,它提供了線程本地的存儲(chǔ)空間。

import threading

local_data = threading.local()

def set_data():
    local_data.value = "這是我的調(diào)料"

def get_data():
    print(local_data.value)

t1 = threading.Thread(target=set_data)
t2 = threading.Thread(target=get_data)

t1.start()
t2.start()

t1.join()
t2.join()

在這里,每個(gè)線程都有自己的local_data,互不影響。

9. 線程異常處理:防患于未然

線程中的異常不會(huì)自動(dòng)傳遞到主線程,需要用try-except捕獲處理。

def risky_task():
    raise ValueError("出錯(cuò)了!")

try:
    t = threading.Thread(target=risky_task)
    t.start()
    t.join()
except ValueError as e:
    print(f"捕獲到異常: {e}")

確保即使線程出錯(cuò),程序也不會(huì)突然崩潰。

10. 實(shí)戰(zhàn)演練:多線程下載

最后,來點(diǎn)實(shí)戰(zhàn)吧,比如多線程下載圖片,體驗(yàn)速度的提升。

import requests
import threading
from queue import Queue

def download_image(url):
    response = requests.get(url)
    with open(f"image_{url[-4:]}", 'wb') as f:
        f.write(response.content)
    print(f"下載完成:{url}")

image_urls = ["http://example.com/image1.jpg", "http://example.com/image2.jpg"]  # 假設(shè)的URL
queue = Queue()
threads = []

for url in image_urls:
    queue.put(url)

def worker():
    while not queue.empty():
        url = queue.get()
        download_image(url)
        queue.task_done()

for _ in range(3):  # 啟動(dòng)3個(gè)下載線程
    t = threading.Thread(target=worker)
    t.start()
    threads.append(t)

# 等待所有下載任務(wù)完成
for t in threads:
    t.join()

print("所有圖片下載完成!")

通過隊(duì)列分配任務(wù)給多個(gè)線程,實(shí)現(xiàn)了并行下載,大大提高了效率。

好啦,今天的探險(xiǎn)就到這里!希望你已經(jīng)對(duì)Python多線程有了更深入的理解。

責(zé)任編輯:趙寧寧 來源: 手把手PythonAI編程
相關(guān)推薦

2024-11-01 08:00:00

2023-10-29 17:12:26

Python編程

2024-02-04 17:21:37

C++編程開發(fā)

2024-05-21 12:18:57

Python代碼重構(gòu)

2024-01-30 00:40:10

2024-05-17 12:43:49

Python編程開發(fā)

2023-06-05 07:56:10

線程分配處理器

2023-04-20 18:45:44

2009-07-03 17:09:01

學(xué)習(xí)Tapestry

2019-02-01 10:05:33

開源游戲開發(fā)游戲引擎

2024-10-16 12:51:56

2024-09-23 12:00:00

Python編程

2021-03-11 09:02:37

SQL數(shù)據(jù)庫數(shù)據(jù)

2024-11-11 08:00:00

PyTorch深度學(xué)習(xí)

2023-05-28 22:48:29

程序員編程

2022-03-09 09:43:20

并發(fā)編程Java

2022-08-16 08:27:20

線程毀線程異步

2024-11-29 08:00:00

代碼安全代碼Python

2022-06-12 23:43:19

SQL數(shù)據(jù)函數(shù)

2022-03-22 23:18:55

SQL技術(shù)內(nèi)部概念
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)