亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

收聽列表??并在附加時做某事

收聽列表??并在附加時做某事

萬千封印 2023-05-23 15:56:32
我有一個 API 監聽傳入的請求并將它們轉儲到列表中。在一個單獨的過程中,我想在附加列表時觸發某種操作。我嘗試實例化一個新進程(來自多處理),但它不會在啟動后更新數組的狀態。from multiprocessing import Processimport timeprocs = []def separateProcess(start, counter):    while True:        time.sleep(1)        print("length of the list from separate Process: "+str(len(procs)))if __name__ == '__main__':    print("program started")    counter = 0    Process(target=separateProcess, args=(counter, counter)).start()    print("program end")    while True:        counter += 1        newstring = "string "+str(counter)        procs.append(newstring)        print("length of the list from main: " + str(len(procs)))        time.sleep(2)這是輸出:length of the list from main: 1length of the list from separate Process: 0length of the list from main: 2length of the list from separate Process: 0length of the list from separate Process: 0length of the list from main: 3length of the list from separate Process: 0length of the list from separate Process: 0
查看完整描述

1 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

創建新的子進程時,它會獲得父進程地址空間的副本,但是任何后續更改(無論是父進程還是子進程)都不會反映在其他進程的內存中。他們每個人都有自己的私人地址空間。

您可以創建一個Manager()并改用其共享列表對象:

import time

??

from multiprocessing import Manager, Process


def separateProcess(start, counter):

? ? while True:

? ? ? ? time.sleep(1)

? ? ? ? print("length of the list from separate Process: "+str(len(procs)))



if __name__ == '__main__':

? ? m = Manager()

? ? procs = m.list()


? ? print("program started")


? ? counter = 0

? ? Process(target=separateProcess, args=(counter, counter)).start()

? ? print("program end")

? ? while True:

? ? ? ? counter += 1

? ? ? ? newstring = "string "+str(counter)

? ? ? ? procs.append(newstring)

? ? ? ? print("length of the list from main: " + str(len(procs)))

? ? ? ? time.sleep(2)

這種方法有一些開銷,因為它會產生一個子進程來托管服務器Manager。


如果您可以調整工作進程邏輯以改為使用隊列,這里有一個示例:


import random

import time


from multiprocessing import cpu_count, Process, Queue



def worker(q):

? ? for item in iter(q.get, 'STOP'):

? ? ? ? t = random.uniform(1, 5)

? ? ? ? print(f'START item: {item}')

? ? ? ? time.sleep(t)

? ? ? ? print(f'END item: {item}, ({t:.3f}s)')



def main():

? ? cpus = cpu_count()

? ? q = Queue()


? ? for i in range(5):

? ? ? ? q.put(i)


? ? for i in range(cpus):

? ? ? ? Process(target=worker, args=(q,)).start()


? ? for i in range(cpus):

? ? ? ? q.put('STOP')



if __name__ == '__main__':

? ? main()


查看完整回答
反對 回復 2023-05-23
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號