如何在 class 中的 Python 中使用多处理

How to use Multiprocessing in Python within a class

我想做的是在我的 class 方法之一上使用多处理。我尝试按照 Python 帮助文件中的示例进行操作,但没有得到预期的结果。这是我的 class 文件:

import os
import telnetlib

class PowerSupply():

    # ---------------------------------- #
    def __init__(self,port_no,my_name):
        self.Status = "Off"
        self.Port = port_no
        self.Name = my_name
        self.tn = None
        self.HOST = "192"
        self.P = Process(target=self.print_time, args=('tname','delay')
        self.P.start()
        self.P.join()
    # ---------------------------------- #
    def TurnOn(self):
        onCommand = "OUT 1\r"

        if self.Status == "ON":
            print "I'm already on"
        else:
            self.tn = telnetlib.Telnet(self.HOST,self.Port)
            self.tn.write(onCommand)
            self.Status = "ON"
            print "I am now on"
    # ---------------------------------- #
    def TurnOff(self):
        offCommand = "OUT 0\r"
        self.tn.write(offCommand)
        self.tn.close()
        print "I am now off"
    # ---------------------------------- #
    def SetVoltage(self,volts):
        voltageCommand = "PV" + " " + str(volts) + "\r"
        self.tn.write(voltageCommand)
    # ---------------------------------- #  
    def GetAllData(self):
        while(self.Status == "ON"):
            self.tn.write("DVC?\r")
            all_data = self.tn.read_some()
            vdc = all_data.split(',')
            vdc = vdc[0]
            print vdc
    # ---------------------------------- #
    def print_time(self, tname, delay):
       count = 0
       while count < 5:
        time.sleep(delay)
        count += 1
        print "%s: %s"%(tname, time.ctime(time.time()))

以下是我尝试使用该实现的方式:

ps1 = PowerSuppy(8000,'L1')
ps1.print_time('thread1',2)
ps1.print_time('thread2',3)

当我尝试像上面那样使用它时,它仍然使用过程方法并且在线程 1 完成之前不调用线程 2。我到底做错了什么,我该如何解决?

好的,这就是我认为该程序将执行的操作:

  1. PowerSuppy(8000,'L1'),它启动一个子进程并调用 self.print_time('tname','delay')。由于 'delay' 不是一个数字,它会立即在子进程中引发一个 TypeError 并结束(所以 self.P.join() 根本没有阻塞)。
  2. ps1.print_time('thread1',2),它运行是主进程中的方法,一直阻塞到结束。
  3. ps1.print_time('thread2',3) 与上一行在主进程中所做的相同。

如何修复:

  1. 不要在__init__方法中初始化子进程,而是在print_time方法中初始化它。
  2. 为子进程的 target 函数实现了一个内部方法。
  3. 不要 运行 Process.join 除非你想 运行 按顺序执行子进程。

代码如下:

import os
import telnetlib

class PowerSupply():

    # ---------------------------------- #
    def __init__(self,port_no,my_name):
        self.Status = "Off"
        self.Port = port_no
        self.Name = my_name
        self.tn = None
        self.HOST = "192"

    # ---------------------------------- #
    def TurnOn(self):
        onCommand = "OUT 1\r"

        if self.Status == "ON":
            print "I'm already on"
        else:
            self.tn = telnetlib.Telnet(self.HOST,self.Port)
            self.tn.write(onCommand)
            self.Status = "ON"
            print "I am now on"
    # ---------------------------------- #
    def TurnOff(self):
        offCommand = "OUT 0\r"
        self.tn.write(offCommand)
        self.tn.close()
        print "I am now off"
    # ---------------------------------- #
    def SetVoltage(self,volts):
        voltageCommand = "PV" + " " + str(volts) + "\r"
        self.tn.write(voltageCommand)
    # ---------------------------------- #  
    def GetAllData(self):
        while(self.Status == "ON"):
            self.tn.write("DVC?\r")
            all_data = self.tn.read_some()
            vdc = all_data.split(',')
            vdc = vdc[0]
            print vdc
    # ---------------------------------- #
    def print_time(self, tname, delay):
        P = Process(target=self._print_time, args=(tname, delay))
        P.start()

    def _print_time(tname, delay):
        count = 0
        while count < 5:
            time.sleep(delay)
        count += 1
        print "%s: %s"%(tname, time.ctime(time.time()))

尝试在您的class中添加一个函数:

def print_time_subprocess(self, tname, delay):
    p = Process(target=self.print_time, args=('tname','delay'))
    p.start()

并用它来测试:

ps1 = PowerSupply(8000,'L1')
ps1.print_time_subprocess('thread1',2)
ps1.print_time_subprocess('thread2',3)

并且不要忘记导入 Process