Python是一種高級編程語言,開發速度快、易於閱讀和編寫,是許多開發者手頭最愛的語言之一。但是它的單線程執行使得開發者在處理大規模數據時遇到了很大的問題。Python多線程技術的引入,能夠使得程序在執行時同時處理多個任務,提升程序運行效率。本文將詳細介紹Python多線程技術的應用和使用。
一、Python多線程的特點
Python多線程允許我們在單個程序中同時運行多個線程,從而實現應用並發執行的同時優化資源所有權。Python多線程技術的特點包括:
1、提升程序運行效率:多線程技術可以同時處理多個任務,加速程序運行。而在單線程執行中,需要等到當前任務執行完畢才能執行下一任務,執行效率較低。
import threading import time def worker(): print(threading.current_thread(), 'start') time.sleep(1) print(threading.current_thread(), 'end') threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) for t in threads: t.start()
2、優化資源利用:多線程技術可以充分利用計算機硬體資源,讓多個線程並行處理任務,從而減少資源浪費。
import threading import time def worker(): lock.acquire() print(threading.current_thread(), 'get lock') time.sleep(1) lock.release() print(threading.current_thread(), 'release lock') lock = threading.Lock() threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) for t in threads: t.start()
3、提高系統可靠性:多線程技術可以將任務分解為多個子任務並行執行,從而減小系統癱瘓的風險。例如,一個子線程掛掉不會影響其他子線程的執行。
import threading import time def worker(): print(threading.current_thread(), 'start') time.sleep(1) print(1/0) print(threading.current_thread(), 'end') threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) for t in threads: t.start()
二、Python多線程的實現
Python多線程的實現依賴於threading庫,它可以很方便地開啟多個線程,從而實現應用並發執行的同時優化資源所有權。以下是Python多線程實現的基本流程:
1、引入threading庫,創建一個線程。
import threading # 創建一個線程t1並執行 def fn(): print('這是一個線程') t1 = threading.Thread(target=fn) t1.start()
2、通過繼承Thread類實現線程。
import threading # 通過繼承Thread類實現 class MyThread(threading.Thread): def __init__(self,name): super().__init__(name=name) def run(self): print('這是一個線程') t1 = MyThread('thread1') t1.start()
3、通過創建線程池實現。
import threading import time from concurrent.futures import ThreadPoolExecutor def worker(number): print('Thread {} starts'.format(number)) time.sleep(1) print('Thread {} ends'.format(number)) executor = ThreadPoolExecutor(max_workers=5) for i in range(5): executor.submit(worker, i) executor.shutdown()
三、Python多線程案例實戰
Python多線程技術可以應用於許多場景中,本文將詳細介紹兩個案例實戰:
1、數據爬取應用案例。多線程技術可以在一定程度上提高爬蟲的效率,當多個線程並發執行時,可以減少單個線程處理請求的等待時間,提高整個爬蟲程序的運行速度。
import requests import threading from queue import Queue class CrawlThread(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while True: url = self.queue.get() try: r = requests.get(url) print(r.content) except Exception as e: print(e) self.queue.task_done() queue = Queue() for i in range(5): t = CrawlThread(queue) t.setDaemon(True) t.start() for j in range(10): queue.put('http://www.baidu.com/') queue.join()
2、並發下載器應用案例。當我們需要下載大量文件時,多線程技術可以顯著提高下載速度。
import requests import threading import os class DownloadThread(threading.Thread): def __init__(self, url, start, end, file): threading.Thread.__init__(self) self.url = url self.start = start self.end = end self.file = file def run(self): headers = {'Range': 'bytes={}-{}'.format(self.start, self.end)} r = requests.get(self.url, headers=headers, stream=True) self.file.seek(self.start) self.file.write(r.content) url = 'https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tar.xz' thread_count = 4 r = requests.head(url) content_length = int(r.headers['Content-Length']) length_per_thread = content_length // thread_count file = open('Python-3.8.0.tar.xz', 'wb') threads = [] for i in range(thread_count): start = i * length_per_thread end = start + length_per_thread - 1 if i != thread_count - 1 else None thread = DownloadThread(url, start, end, file) thread.start() threads.append(thread) for thread in threads: thread.join() file.close()
總結
本文通過介紹Python多線程技術的特點、實現和案例實戰,詳細闡述了Python多線程技術的用法和應用場景,旨在幫助開發者更好地利用Python多線程技術提升程序執行效率,提高應用的並發執行能力。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/252910.html