Python多線程:提升程序運行效率的利器

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

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-14 02:15
下一篇 2024-12-14 02:15

相關推薦

  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • Python程序文件的拓展

    Python是一門功能豐富、易於學習、可讀性高的編程語言。Python程序文件通常以.py為文件拓展名,被廣泛應用於各種領域,包括Web開發、機器學習、科學計算等。為了更好地發揮P…

    編程 2025-04-29
  • Python購物車程序

    Python購物車程序是一款基於Python編程語言開發的程序,可以實現購物車的相關功能,包括商品的添加、購買、刪除、統計等。 一、添加商品 添加商品是購物車程序的基礎功能之一,用…

    編程 2025-04-29
  • Python多線程讀取數據

    本文將詳細介紹多線程讀取數據在Python中的實現方法以及相關知識點。 一、線程和多線程 線程是操作系統調度的最小單位。單線程程序只有一個線程,按照程序從上到下的順序逐行執行。而多…

    編程 2025-04-29
  • lsw2u1:全能編程開發工程師的利器

    lsw2u1是一款多功能工具,可以為全能編程開發工程師提供便利的支持。本文將從多個方面對lsw2u1做詳細闡述,並給出對應代碼示例。 一、快速存取代碼段 在日常開發中,我們總會使用…

    編程 2025-04-29
  • Python刷課:優化學習體驗的利器

    Python刷課作為一種利用自動化技術優化學習體驗的工具已經被廣泛應用。它可以幫助用戶自動登錄、自動答題等,讓用戶在學習過程中可以更加專註於知識本身,提高效率,增加學習樂趣。 一、…

    編程 2025-04-29
  • 爬蟲是一種程序

    爬蟲是一種程序,用於自動獲取互聯網上的信息。本文將從如下多個方面對爬蟲的意義、運行方式、應用場景和技術要點等進行詳細的闡述。 一、爬蟲的意義 1、獲取信息:爬蟲可以自動獲取互聯網上…

    編程 2025-04-29
  • Vb運行程序的三種方法

    VB是一種非常實用的編程工具,它可以被用於開發各種不同的應用程序,從簡單的計算器到更複雜的商業軟體。在VB中,有許多不同的方法可以運行程序,包括編譯器、發布程序以及命令行。在本文中…

    編程 2025-04-29

發表回復

登錄後才能評論