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

Python多線程編程全解析:基礎(chǔ)到高級用法

開發(fā) 后端
Python的Threading模塊提供了多線程編程的基本工具。在下面,我將列舉一些基礎(chǔ)的多線程用法和一些高級用法,并提供相應(yīng)的源代碼,其中包含中文注釋。

Python中有多線程的支持。Python的threading模塊提供了多線程編程的基本工具。在下面,我將列舉一些基礎(chǔ)的多線程用法和一些高級用法,并提供相應(yīng)的源代碼,其中包含中文注釋。

基礎(chǔ)用法:

創(chuàng)建和啟動線程

import threading
import time

# 定義一個簡單的線程類
class MyThread(threading.Thread):
    def run(self):
        for _ in range(5):
            print(threading.current_thread().name, "is running")
            time.sleep(1)

# 創(chuàng)建兩個線程實例
thread1 = MyThread(name="Thread-1")
thread2 = MyThread(name="Thread-2")

# 啟動線程
thread1.start()
thread2.start()

# 主線程等待所有子線程結(jié)束
thread1.join()
thread2.join()

print("Main thread exiting")

線程同步 - 使用鎖

import threading

# 共享資源
counter = 0

# 創(chuàng)建鎖
counter_lock = threading.Lock()

# 定義一個簡單的線程類
class MyThread(threading.Thread):
    def run(self):
        global counter
        for _ in range(5):
            with counter_lock:  # 使用鎖保護(hù)臨界區(qū)
                counter += 1
                print(threading.current_thread().name, "Counter:", counter)

# 創(chuàng)建兩個線程實例
thread1 = MyThread(name="Thread-1")
thread2 = MyThread(name="Thread-2")

# 啟動線程
thread1.start()
thread2.start()

# 主線程等待所有子線程結(jié)束
thread1.join()
thread2.join()

print("Main thread exiting")

高級用法:

使用線程池

import concurrent.futures
import time

# 定義一個簡單的任務(wù)函數(shù)
def task(name):
    print(f"{name} is running")
    time.sleep(2)
    return f"{name} is done"

# 使用線程池
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    # 提交任務(wù)給線程池
    future_to_name = {executor.submit(task, f"Thread-{i}"): f"Thread-{i}" for i in range(5)}

    # 獲取任務(wù)結(jié)果
    for future in concurrent.futures.as_completed(future_to_name):
        name = future_to_name[future]
        try:
            result = future.result()
            print(f"{name}: {result}")
        except Exception as e:
            print(f"{name}: {e}")

使用Condition進(jìn)行線程間通信

import threading
import time

# 共享資源
shared_resource = None

# 創(chuàng)建條件變量
condition = threading.Condition()

# 定義一個寫線程
class WriterThread(threading.Thread):
    def run(self):
        global shared_resource
        for _ in range(5):
            with condition:
                shared_resource = "Write data"
                print("Writer wrote:", shared_resource)
                condition.notify()  # 通知等待的線程
                condition.wait()  # 等待其他線程通知

# 定義一個讀線程
class ReaderThread(threading.Thread):
    def run(self):
        global shared_resource
        for _ in range(5):
            with condition:
                while shared_resource is None:
                    condition.wait()  # 等待寫線程通知
                print("Reader read:", shared_resource)
                shared_resource = None
                condition.notify()  # 通知寫線程

# 創(chuàng)建寫線程和讀線程
writer_thread = WriterThread()
reader_thread = ReaderThread()

# 啟動線程
writer_thread.start()
reader_thread.start()

# 主線程等待所有子線程結(jié)束
writer_thread.join()
reader_thread.join()

print("Main thread exiting")

這些例子涵蓋了一些基礎(chǔ)和高級的多線程用法。請注意,在Python中由于全局解釋器鎖(GIL)的存在,多線程并不能充分利用多核處理器。如果需要充分利用多核處理器,可以考慮使用multiprocessing模塊進(jìn)行多進(jìn)程編程。

責(zé)任編輯:姜華 來源: 今日頭條
相關(guān)推薦

2023-10-27 08:42:56

Python字典

2009-03-12 10:52:43

Java線程多線程

2011-06-13 10:41:17

JAVA

2025-02-08 07:00:00

2023-06-12 08:30:08

多線程編程線程調(diào)試

2011-07-01 17:50:13

Python 多線程

2021-03-01 11:20:13

網(wǎng)絡(luò)安全多線程代碼

2017-03-08 14:18:37

Linux多線程編程

2021-08-12 14:33:20

Python多線程編程

2013-07-16 10:12:14

iOS多線程多線程概念多線程入門

2011-06-22 16:18:23

QT 多線程 QSocket

2023-06-13 13:39:00

多線程異步編程

2024-10-16 09:34:50

2023-10-18 15:19:56

2011-06-02 17:27:49

iphone 多線程

2010-03-03 17:44:07

Python多線程

2023-04-02 17:53:10

多線程編程自測

2023-06-05 07:56:10

線程分配處理器

2023-06-06 08:17:52

多線程編程Thread類

2023-06-07 13:49:00

多線程編程C#
點贊
收藏

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