簡體   English   中英

如何在Python中將Class賦予子進程?

[英]How to give Class to child process in python?

from multiprocessing import Process, Pipe

def f(a1):
    print a1.name
    a1.conn2.send('why!?!?!?!?!!?!??')
    a1.conn2.close()

class test1:
    name = 'this is name in class'
    conn1,conn2 = Pipe()

if __name__ == '__main__':
    a1 = test1

    p = Process(target=f, args=(a1,))
    p.start()
    print a1.conn1.recv()
    p.join()

我必須給子進程多個參數,並在父子之間進行管道通信。

因此,我嘗試將Class賦予子進程包括管道。

但是此代碼的子進程無法發送任何內容。

所以父進程掛在recv().....

怎么解決呢? 幫我吧... TT

PS:這是python 2.7

假設您使用的是Windows:

您將在類test1靜態初始化Pipes,因此在創建新進程時(當您調用start() ),將重新創建test1類並與之一起創建Pipe。 這意味着在新進程中運行的函數完全使用了另一個Pipe。

這可以通過在test1 實例中創建Pipes來解決(或直接傳遞連接):

from multiprocessing import Process, Pipe

def f(a1):
    print a1.name
    a1.conn2.send('why!?!?!?!?!!?!??')
    a1.conn2.close()

class Test1(object):

    def __init__(self):
        self.name = 'this is name in class'
        self.conn1, self.conn2 = Pipe()

if __name__ == '__main__':
    a1 = Test1()

    p = Process(target=f, args=(a1,))
    p.start()
    print a1.conn1.recv()
    p.join()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM