Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the effect of thread pool model with Python

Shulou Source: shulou.com Published: 2022-06-02 22:42:01 10月05日 Update

Today, I will talk to you about how to use Python to achieve the effect of the thread pool model, many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

This article provides you with python code to achieve a simple thread effect source code case. Python's multithreaded crawler has always been a relatively concerned item for people learning python.

The body of the python simple threading model code is as follows:

`#-*-encoding: UTF-8-*-```# Encoding statement ``import``threading,queue, os``` # Import method module ``def``main (inargs): ``work_ queue`` = ``queue.Queue () ``# queue class implements the lock ``for`i`in`in`range`` (``3``): ````sets 3 child processes ``worker` = ``Worker (work_queue) I) ```# worker thread, work queue, thread number ``worker.daemon` = ``True`` daemon` daemon` ``True`` daemon` ``worker.start ()`` # start thread start ``for`elemt`in``inargs: ``work _ queue.put (elemt) ``# join the queue to start each thread ``worker.daemon` = ``True`` Worker (threading.Thread):`` # inherit thread class Class is also a difficult part to learn: ``def`` _ init__ (``self``, work_queue,number): ``super`` (). _ _ init__ () ``self`.work _ queue`` = ``work_queue ``self`.number`` = `number``def``process (``self``, elemt): ``# custom thread processing function Used in run (). ``# here only prints the thread number and the incoming parameter ``print`` (`` "\ n {0} task:---- {1}" ``. `format`` (``self`.number) Elemt) ``def``run (``self``): ``# overload the run () ``while`True``: `try`` in the threading class: ``elemt` = ``self`.work _ queue.get () ```# take the task ``self`.process (elemt) `finally``: `self`.work _ queue.task_done () ``# notify queue that a task before queue has completed ``if``_ name__`` = ``"_ main__ "``: ``main (os.listdir (```"."``)) ``# this step is to use the current directory After reading the above content, I have finished the test of the file name. Do you have any further understanding of how to implement the thread pool model with Python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Threads queues effects models content code processes parts study work size people tasks functions parameters masterpieces files methods more cases Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi MariaDB NVidia MySQL Huawei