Python3多线程详解

yizhihongxing

Python3多线程详解

Python3中的多线程模块是_threadthreading_thread是低级模块,thread是高级模块,对_thread`进行了封装,使得使用更加方便。本文将详细介绍Python3多线程的使用方法。

创建线程

Python中创建线程有两种方式:使用_thread模块和使用threading模块。下面是两种方式的示例:

使用_thread模块

import _thread
import time

def print_time(thread_name, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print(f"{thread_name}: {time.ctime(time.time())}")

try:
    _thread.start_new_thread(print_time, ("Thread-1", 1))
    _thread.start_new_thread(print_time, ("Thread-2", 2))
except:
    print("Error: 无法启动线程")

while True:
    pass

在这个示例中,我们使用_thread模块创建了两个线程,分别执行print_time函数。print_time函数会打印当前时间,并在指定的延迟后再次打印。在主线程中,我们使用一个无限循环来保持程序运行,直到手动停止。

使用threading模块

import threading
import time

class MyThread(threading.Thread):
    def __init__(self, thread_name, delay):
        threading.Thread.__init__(self)
        self.thread_name = thread_name
        self.delay = delay

    def run(self):
        count = 0
        while count < 5:
            time.sleep(self.delay)
            count += 1
            print(f"{self.thread_name}: {time.ctime(time.time())}")

try:
    thread1 = MyThread("Thread-1", 1)
    thread2 = MyThread("Thread-2", 2)
    thread1.start()
    thread2.start()
except:
    print("Error: 无法启动线程")

while True:
    pass

在这个示例中,我们使用threading模块创建了两个线程,分别执行MyThread类的run方法。MyThread类继承自threading.Thread类,并重写了run方法。在run方法中,我们执行了与_thread示例中相同的操作。在主线程中,我们使用一个无限循环来保程序运行,直到手动停止。

线程同步

在多线程编程中,线程同步是一个非常重要的问题。Python3中提供了多种方式来实现线程同步,例如使用锁、信号量、事件等。下面是一个使用锁实现线程同步的示例:

import threading
import time

class Counter:
    def __init__(self):
        self.value = 0
        self.lock = threading.Lock()

    def increment(self):
        with self.lock:
            self.value += 1

def worker(counter):
    for i in range(100000):
        counter.increment()

if __name__ == '__main__':
    counter = Counter()
    threads = [threading.Thread(target=worker, args=(counter,)) for i in range(10)]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    print(counter.value) # 输出1000000

在这个示例中,我们定义了一个名为Counter的类,该类包含一个value属性和一个lock属性。increment方法使用with语句获取锁,并将value属性加1。在worker函数中,我们创建了10个线程,并让每个线程执行100000次counter.increment()操作。在主线程中,我们等待所有线程执行完毕,并输出counter.value的值。

线程池

在多线程编程中,线程池是一个非常有用的工具,可以避免频繁创建和销毁线程的开销。Python中提供了concurrent.futures模块,可以方便地创建线程池。下面是一个使用线程池的示例:

import concurrent.futures
import time

def worker(delay):
    time.sleep(delay)
    return delay

if __name__ == '__main__':
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        results = executor.map(worker, [1, 2, 3, 4, 5])
        for result in results:
            print(result)

在这个示例中,我们定义了一个名为worker的函数,该函数会在指定的延迟后返回延迟的时间。在主线程中,使用ThreadPoolExecutor创建了一个最大工线程数为2的线程池。我们使用map方法将worker函数应用于输入的值,并在循环中输出结果。

示例说明

下面是一个示例,演示了如何使用多线程和requests库实现并发HTTP请求:

import threading
import requests

def fetch(url):
    response = requests.get(url)
    print(response.text)

threads = [threading.Thread(target=fetch, args=(f'https://www.baidu.com/?page={i}',)) for i in range(10)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

在这个示例中,我们定义了一个名为fetch的函数,它使用requests库来发送HTTP请求并输出响应的文本内容。在主程序中,我们创建了10个线程,并让每个线程执行fetch函数。在主程序中,我们等待所有线程执行完毕。

下面是另一个示例,演示了如何使用多线程和Pillow库实现图片处理:

import threading
from PIL import Image

def process_image(image_path):
    with Image.open(image_path) as image:
        image = image.rotate(90)
        image.save(f'processed_{image_path}')

threads = [threading.Thread(target=process_image, args=(f'image_{i}.jpg',)) for i in range(10)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

在这个示例中,我们定义了一个名为process_image的函数,它使用Pillow库来旋转图片并保存处理后的图片。在主程序中,我们创建了10个线程,并让每个线程执行process_image函数。在主程序中,我们等待所有线程执行完毕。

总结

本文介绍了Python3多线程的使用方法,包括创建线程、线程同步和线程池。在实际应用中,我们需要根据具体情况选择合适的方法以确保程序的正确性和效率。同时,本文提供两个示例说明,演示了如何使用多线程实现并发HTTP请求和图片处理。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python3多线程详解 - Python技术站

(0)
上一篇 2023年5月13日
下一篇 2023年5月13日

相关文章

  • 如何使用Numpy模块裁剪图片

    使用Numpy模块裁剪图片的完整攻略如下: 1. 导入Numpy和OpenCV模块 首先需要导入Numpy和OpenCV模块,Numpy是Python科学计算的基础模块,用于处理数组的高效算法,而OpenCV则是计算机视觉领域的重要模块,提供了很多图像处理的函数和工具。 import numpy as np import cv2 2. 读入图片 读入要裁剪的…

    python-answer 2023年3月25日
    00
  • python 检查文件mime类型的方法

    当我们需要确定一个文件的类型时,可以采用MIME类型来进行检查。MIME类型是一种由多用途互联网邮件扩展(MIME)引入的标准。它是一种用来标识文件格式的字符串,通常由文件的后缀名来确定。 在Python中,使用mimetypes模块可以进行MIME类型检查。下面是如何使用mimetypes进行文件MIME类型检查的完整攻略: 1. 导入mimetypes模…

    python 2023年5月20日
    00
  • python基础之reverse和reversed函数的介绍及使用

    Python基础之reverse和reversed函数的介绍及使用 在 Python 中,有两个与列表倒序相关的函数:reverse() 和 reversed()。虽然两者的名称相似,但它们的使用方法和返回结果却有所不同。 reverse() 函数 reverse() 函数是针对列表本身进行操作,它将列表中的元素顺序进行反转,使得列表成为倒序的形式。例如: …

    python 2023年5月14日
    00
  • Python爬虫中的并发编程详解

    Python爬虫中的并发编程详解 在Python爬虫中,为了提高爬虫效率,通常需要使用并发编程。本文将介绍Python爬虫中的并发编程,包括多线程、协程和异步IO等技术。同时,还会提供两个示例讲解。 多线程 多线程是指在一个进程中存在多个线程,每个线程都可以独立执行不同的任务。在Python中,可以使用threading模块实现多线程编程。 下面是一个简单的…

    python 2023年5月14日
    00
  • 为什么我的 OR 运算符不能在 python 中工作?

    【问题标题】:Why is my OR operator not working in python?为什么我的 OR 运算符不能在 python 中工作? 【发布时间】:2023-04-06 03:56:01 【问题描述】: while scr_1 &lt;= 4 or scr_2 &lt;= 4 :#scr 代表分数 这里发生的事情是我的…

    Python开发 2023年4月7日
    00
  • Python matplotlib绘制xkcd动漫风格的图表

    下面是“Python matplotlib绘制xkcd动漫风格的图表”的完整攻略: 一、背景介绍 Python的matplotlib是一个十分强大的绘图库,可以用来生成各种类型的图表。而xkcd则是一种流行的漫画风格,具有幽默风趣的特点。本文将介绍如何使用Python的matplotlib库来绘制xkcd动漫风格的图表。 二、准备工作 首先需要安装matpl…

    python 2023年6月6日
    00
  • Python自然语言处理 NLTK 库用法入门教程【经典】

    以下是Python自然语言处理NLTK库用法入门教程的完整攻略: 步骤1:安装NLTK库 在使用NLTK库之前,需要安装NLTK库。以下是一个示例代码: pip install nltk 在这个例子中,我们使用pip命令安装了NLTK库。 步骤2:导入NLTK库 在使用NLTK库之前,需要导入NLTK库。以下是一个示例代码: import nltk 在这个例…

    python 2023年5月14日
    00
  • Python机器学习之Kmeans基础算法

    以下是关于“Python机器学习之Kmeans基础算法”的完整攻略: 简介 Kmeans是一种常见的聚类算法,它可以将数据集分成多个簇。Python中有多种库可以实现Kmeans算法,例如scikit-learn和numpy。本教程将介绍如何使用Python实现Kmeans基础算法,并提供两个示例。 Kmeans算法 Kmeans算法是一种迭代算法,它将数据…

    python 2023年5月14日
    00
合作推广
合作推广
分享本页
返回顶部