当前位置:网站首页>Multithreading and concurrent programming (2)
Multithreading and concurrent programming (2)
2022-07-06 07:09:00 【And ν】
Catalog
Multithreading and concurrent programming ( Two )
Process creation -Proccess Subclass
Multithreading and concurrent programming ( Two )
Process creation -Proccess Subclass
You can also create processes by using classes , You can customize - One class , Inherit Process class , Every time this class is instantiated , Is equivalent to instantiating a process object .
[ Example ] Inherit Process Class , rewrite run0 Method to create a process
# The import module
from multiprocessing import Process
from time import sleep
import time
# Defining classes
class ClockProcess(Process):
# Reinitialize the method
def __init__(self,interval):
Process.__init__(self)
self.interval=interval
def run(self):
# Create child process
print(" The time when the subprocess starts executing :{}".format(time.ctime()))
sleep(self.interval)
print(" Sub process execution end time :{}".format(time.ctime()))
if __name__ =="__main__":
p=ClockProcess(4)
p.start()
p.join()
print(" End of main process ")The process of pool
Using Python When it comes to system management , In particular, operating multiple file directories at the same time , Or remote control of multiple hosts , Parallel operation can save a lot of time . When the number of objects to be manipulated is small , Can be used directly multiprocessing Medium Process Dynamic generation of multiple processes , A dozen are fine , But if it's a hundred , Thousands of goals , Manually limiting the number of processes is too cumbersome , At this time, it can play the role of process pool .
Pool Can provide a specified number of processes , For users to call , When a new request is submitted to pool In the middle of the day , If the pool is not full , Then it will create - A new process Used to execute the request ; But if the number of processes in the pool has reached the specified maximum , Then the request will wait , Until there are processes in the pool , To create a new process .Pool The syntax of is as follows :
Pool ([numprocess [ initializer [, initrg]])among numprocess Is the number of processes to create . If you omit this parameter , Will use cpu _count() Value .Initializer Is the callable object to be executed when each worker process starts .Initargs It's to pass on to initializer Parameter Yuanzu .Initializer The default is None.
Pool Example method table
| Method | describe |
|---|---|
| apply (fune [, args, [, kwargs]]) | Execute functions in a pool worker process (*arss, **kwares), And then return the result . |
| apply_async(func,[,args[,kwargs[,callback]]]) | stay Functions are executed asynchronously in a pool worker process (*arss, **kwarss), And then return the result . The result of this method is AsyncResult Class , It can be used later to get the final result .Callback Is a callable object , Accept input parameters . When func When the result of becomes available , Pass on to immediately callback. Callback Do not perform any blocking operations , Otherwise, it will block receiving the results of other asynchronous operations . |
| close() | Close process pool , Prevent from entering - - Step by step . If there are still pending operations , They will be completed before the work process is terminated |
| join() | Wait for all worker processes to exit . This method can only be used in close () perhaps terminate () Call after method |
| imap( func, iterable [,chunksize] ) | map () One of the versions of the function , Return iterators instead of result lists |
| imap unordered( fune. ,iterable [ ,chunksize] ) | Same as imap() The function is the same , Only the order of results is arbitrarily determined according to the time received from the work process |
| map( func, iterable [,chunksize] ) | The callable object fune Apply to iterable. All items in , Then return the results in the form of a list . By way of iterable Divide into blocks and assign work to work processes , This operation can be performed in parallel .chunksize. Specify the number of items in each block . If the quantity is large , Can increase chunksize. To improve performance |
| map_ asyne( fune, iterable[, chunksize[,callback]] ) | Same as map () function , But the result is returned asynchronously . The return value is AsyncResult Class , Available later and get results .Callback An adjustable object that accepts a parameter . Provided callable, When the results become available , Will call... With the result callable. |
| terminate() | That is, terminate all working processes , At the same time, do not perform any cleanup or end any pending work . If p Be recycled , This function will be called automatically . |
| get( [ timeout] ) | Return results , Wait for results to arrive if necessary .Timeout Is an optional timeout . If the result does not arrive within the specified time , Will lead to multiprocessing. TimeoutError abnormal . If an exception is thrown in a remote operation , It will be raised again when this method is called |
| ready() | If the call is complete , Then return to True |
| sucessful() | If the call completes without throwing an exception , return True. Call this method before the result is ready. , Will lead to AssertionError abnormal |
| wait( [timeout] ) | Wait for results to become available .Timeout Is an optional timeout |
Be careful :
apply_ async(func[, args[, kwds[, callback]]) It's non blocking ,apply(func[, args[, kwds]) It's blocked
[ Example ] Use of process pools ( Non blocking )
# The import module
import multiprocessing
import time
# The task function executed by the process
def func(msg):
print('start',msg)
time.sleep(3)
print('end',msg)
if __name__=='__main__':
# Create initialization 3 The process pool of
pool=multiprocessing.Pool(3)
# Add tasks
for i in range(1,6):
msg=' Mission %d'%i
pool.apply_async(func,(msg,))
# If the process no longer receives new requests call close
pool.close()
# Wait for the subprocess to finish
pool.join()
边栏推荐
- BUU的MISC(不定时更新)
- Yield method of tread
- 【Hot100】739. 每日温度
- Cookie技术&Session技术&ServletContext对象
- Supporting title of the book from 0 to 1: ctfer's growth road (Zhou Geng)
- Idea console color log
- Internal and external troubles of "boring ape" bayc
- After working for 10 years, I changed to a programmer. Now I'm 35 + years old and I'm not anxious
- Uni app third party package configuration network request
- 《从0到1:CTFer成长之路》书籍配套题目(周更)
猜你喜欢

顶测分享:想转行,这些问题一定要考虑清楚!

配置树莓派接入网络

leetcode704. Binary search (find an element, simple, different writing)

19. Actual memory management of segment page combination

leetcode6109. 知道秘密的人数(中等,周赛)

【每日一题】729. 我的日程安排表 I

leetcode704. 二分查找(查找某个元素,简单,不同写法)

攻防世界 MISC中reverseMe简述

Hydra common commands

Simple use of MySQL database: add, delete, modify and query
随机推荐
NFT on fingertips | evaluate ambire on G2, and have the opportunity to obtain limited edition collections
How are the open source Netease cloud music API projects implemented?
When my colleague went to the bathroom, I helped my product sister easily complete the BI data product and got a milk tea reward
leetcode1020. 飞地的数量(中等)
[some special grammars about C]
Raspberry pie 3B update VIM
巴比特 | 元宇宙每日必读:中国互联网企业涌入元宇宙的群像:“只有各种求生欲,没有前瞻创新的雄心”...
Arduino tutorial - Simon games
前缀和数组系列
LeetCode 78:子集
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models. common‘ from ‘/home/yolov5/models/comm
[advanced software testing step 1] basic knowledge of automated testing
因高额网络费用,Arbitrum 奥德赛活动暂停,Nitro 发行迫在眉睫
Database basics exercise part 2
leetcode59. 螺旋矩阵 II(中等)
win10 64位装三菱PLC软件出现oleaut32.dll拒绝访问
MVVM of WPF
Lesson 12 study notes 2022.02.11
SEO学习的最好方式:搜索引擎
After sharing the clone remote project, NPM install reports an error - CB () never called! This is an error with npm itself.