search
HomeBackend DevelopmentPython TutorialWhat is the reason why the Python process pool handles concurrent TCP requests and causes the client to get stuck?

The root cause and solution for the Python process pool to process concurrent TCP requests and causes client jamming

This article analyzes the reasons why the client may get stuck when using Python process pool to handle concurrent TCP requests and provides an effective solution.

Problem: The server uses multiprocessing.Pool to create a process pool to process TCP requests, and the client uses ThreadPoolExecutor to send requests concurrently. On macOS system, when the client thread pool max_workers is greater than 1, the client will be stuck; but it runs normally on Ubuntu system. The server code uses pool.apply_async to allocate tasks non-blocking, and there seems to be no blocking problem.

The root cause: The server code passes socket object directly to the child process. Since socket object cannot be shared directly between processes, the child process fails when trying to copy socket object, causing the child process to fail to work properly and block client requests.

Solution: Avoid passing socket objects directly, but pass their file descriptors (file descriptors).

Improved server code:

 import os
import socket
import sys
import time
import threading
from loguru import logger
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures._base import Future
import multiprocessing

default_encoding: str = 'utf-8'

def init_serversocket() -> socket.socket:
    # ... (The code is the same as the original question description) ...

def send_response(clientsocket: socket.socket, addr: tuple, response_body: bytes) -> int:
    # ... (The code is the same as the original question description) ...

def start_request(clientsocket_fd: int, addr: tuple) -> int:
    clientsocket = socket.fromfd(clientsocket_fd, socket.AF_INET, socket.SOCK_STREAM)
    os.close(clientsocket_fd) # Close the original file descriptor to prevent resource leakage try:
        # ... (The code is the same as the original question description) ...
    except Exception as error:
        logger.exception(error)
    Finally:
        clientsocket.close()

def worker_process(clientsocket_fd, addr):
    start_request(clientsocket_fd, addr)

if __name__ == "__main__":
    serversocket = init_serversocket()

    pool = multiprocessing.Pool(processes=16)

    While True:
        try:
            clientsocket, addr = serversocket.accept()
            clientsocket_fd = clientsocket.fileno()
            pool.apply_async(worker_process, (clientsocket_fd, addr))
        except Exception as error:
            logger.exception(error)

    pool.close()
    pool.join()

Improvement instructions:

  1. The start_request function now receives clientsocket 's file descriptor clientsocket_fd .
  2. The socket.fromfd function rebuilds the socket object based on the file descriptor to ensure that the child process can operate the socket correctly.
  3. Add clientsocket.close() in finally block to make sure the socket is closed correctly.
  4. The worker_process function handles clientsocket_fd and closes the file descriptor in the child process to avoid resource leakage.

By passing file descriptors instead of socket objects themselves, the problem of inter-process communication is solved, thereby avoiding the problem of client jamming. This method ensures correct handling of TCP connections in a multi-process environment.

What is the reason why the Python process pool handles concurrent TCP requests and causes the client to get stuck?

The above is the detailed content of What is the reason why the Python process pool handles concurrent TCP requests and causes the client to get stuck?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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),

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.