search
HomeBackend DevelopmentPython TutorialPython multi-threading and multi-process: practical case analysis, master the application skills of concurrent programming

Python 多线程与多进程:实战案例剖析,掌握并发编程的应用技巧

1. Multi-threading

MultipleThreads is a concurrent programming technology that allows a program to perform multiple tasks at the same time. In Python, you can use the threading module to create and manage threads. Threads share the program's memory space, so data can be shared easily. However, there are also some challenges in multi-threaded programming, such as thread safety issues and dead lock issues. 2. Multi-process Multiple processes is a

concurrency

programming technology that allows one program to perform multiple tasks at the same time. In Python, you can use the multiprocessing module to create and manage processes. The process is independent of the program's memory space, so there are no thread safety issues. However, multi-process programming also presents some challenges, such as inter-process communication and synchronization issues. 2. Practical Case 1: Using multi-threads to accelerate image processing

Requirements: There is a folder containing 1000 images, and each image needs to be processed, including resizing, sharpening, and adding watermarks.

Solution:

You can use multi-threading to speed up image processing. Specific steps are as follows:

First, save the list of image files in a list.

Then, use the threading module to create a thread pool

.
  1. Next, assign image processing tasks to threads in the thread pool.
  2. Finally, wait for all threads to complete their tasks and then save the processed image to the file.
  3. By using multi-threading, the image processing time can be greatly shortened.
  4. import threading
    import os
    from PIL import Image, ImageFilter
    
    def process_image(image_path):
    image = Image.open(image_path)
    image = image.resize((256, 256))
    image = image.filter(ImageFilter.SHARPEN)
    image.save(image_path)
    
    def main():
    # 获取图像文件列表
    image_files = os.listdir("images")
    
    # 创建线程池
    pool = ThreadPool(4)
    
    # 将图像处理任务分配给线程池
    for image_file in image_files:
    pool.submit(process_image, ("images/" + image_file, ))
    
    # 等待所有线程完成任务
    pool.close()
    pool.join()
    
    if __name__ == "__main__":
    main()
  5. 3. Practical Case 2: Using multiple processes to accelerate scientific computing
Requirements:

A scientific calculation needs to be performed, involving a large number of floating point calculations.

Solution:

Multiple processes can be used to speed up scientific computing. Specific steps are as follows:

First, decompose the scientific computing task into multiple subtasks.

Then, use the multiprocessing module to create a process pool.

Next, assign subtasks to processes in the process pool.
  1. Finally, wait for all processes to complete their tasks, and then summarize the results of the subtasks.
  2. By using multiple processes, the time for scientific calculations can be greatly shortened.
  3. import multiprocessing
    import math
    
    def compute_pi(n):
    result = 0
    for i in range(n):
    result += 4 * (-1)**i / (2*i + 1)
    return result
    
    def main():
    # 分解科学计算任务
    n = 100000000
    num_processes = 4
    sub_tasks = [n // num_processes] * num_processes
    
    # 创建进程池
    pool = multiprocessing.Pool(num_processes)
    
    # 将子任务分配给进程池
    results = pool.map(compute_pi, sub_tasks)
    
    # 等待所有进程完成任务
    pool.close()
    pool.join()
    
    # 汇总子任务的结果
    pi = sum(results)
    
    print("π =", pi)
    
    if __name__ == "__main__":
    main()
  4. IV.
  5. Summary

Through the above two practical cases, we have seen the powerful power of multi-threading and multi-process in concurrent programming. In actual

development

, we can choose appropriate concurrent programming technology according to specific needs.

The above is the detailed content of Python multi-threading and multi-process: practical case analysis, master the application skills of concurrent programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:编程网. If there is any infringement, please contact admin@php.cn delete
How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

How to solve the permissions problem encountered when viewing Python version in Linux terminal?How to solve the permissions problem encountered when viewing Python version in Linux terminal?Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

What are some popular Python libraries and their uses?What are some popular Python libraries and their uses?Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

Scraping Webpages in Python With Beautiful Soup: Search and DOM ModificationScraping Webpages in Python With Beautiful Soup: Search and DOM ModificationMar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

How to Create Command-Line Interfaces (CLIs) with Python?How to Create Command-Line Interfaces (CLIs) with Python?Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),