併發程式設計 程序池與執行緒池 練習3

2022-09-09 09:03:11 字數 1402 閱讀 7843

通過繼承multipocessing類,實現乙個程序池。

#

coding = utf-8

'''實現乙個程序池

'''import

time

import

multiprocessing

from multiprocessing import

manager, queue

class

myprocess(object):

def__init__

(self, num):

super().

__init__

()

#self.queue = manager().queue()

self.queue =multiprocessing.joinablequeue()

for i in range(1, num+1):

multiprocessing.process(target=self.work, daemon=true).start()

defwork(self):

'''從佇列獲取任務並執行

:return:

'''while

true:

try:

func, args, kwargs =self.queue.get()

func(*args, **kwargs)

except

exception as e:

print

(e)

finally

: self.queue.task_done()

'''接收任務,並將其存入到佇列中

:param func:

:param args:

:param kwargs:

:return:

'''self.queue.put((func, args, kwargs))

defjoin(self):

'''控制程序結束

:return:

'''self.queue.join()

deffunc1():

print('

111'

) time.sleep(2)

deffunc2():

print('

222'

) time.sleep(2)

deffunc3():

print('

333')if

__name__ == '

__main__':

process = myprocess(2)

process.join()

print('

任務結束!

')

併發程式設計 程序池與執行緒池 練習2

通過繼承threading類,實現乙個執行緒池 coding utf 8 自己實現乙個執行緒池 import time import queue import threading class mythreadpool object def init self,num super init self....

併發程式設計 程序池與執行緒池 練習1

實現執行緒的反覆呼叫 用乙個執行緒執行多個任務 import threading import queue class mythread threading.thread 通過一些方法實現執行緒的反覆呼叫 def init self super init self.queue queue.queue...

併發程式設計 執行緒池與程序池

以時間換空間 程序池 乙個容器,這個容器限制住你開啟程序的數量,預設是os.cpu count 我的電腦是8核,所以能開啟8個,第一次肯定只能並行的處理8個任務,只要有任務完成,程序馬上就會接下乙個任務。實現 from concurrent.futures import processpoolexe...