0

嗨,我正在创建这个工作生成器类,我在终止时挂起我知道我需要使用 a.join来关闭它们,但我不知道如何将进程名称传递给terminate函数。我的想法是以某种方式将其保存到全局变量中,我在想一本字典。然后,当需要终止工作人员时,可以terminate访问该函数变量并在将毒丸放入消息队列后终止适用的进程

class worker_manager:
      i = test_imports()
      #someVarForP 
      #someVarForP2 

      def generate(control_queue, threadName, runNum):
          if threadName == 'one':
              print ("Starting import_1 number %d") % runNum
              p = multiprocessing.Process(target=i.import_1, args=(control_queue, runNum))
              #someVarForP = p
              p.start()        
          if threadName == 'two': 
              print ("Starting import_2 number %d") % runNum
              p = multiprocessing.Process(target=i.import_2, args=(control_queue, runNum))
              #someVarForP2 = p2
              p.start()
          if threadName == 'three':    
              p = multiprocessing.Process(target=i.import_1, args=(control_queue, runNum))
              print ("Starting import_1 number %d") % runNum
              p2 = multiprocessing.Process(target=i.import_2, args=(control_queue, runNum))
              print ("Starting import_2 number %d") % runNum
              #someVarForP = p
              #someVarForP2 = p2
              p.start()
              p2.start()

      def terminate(threadName):
           if threadName == 'one':
               #self.someVarForP.join()
           if threadName == 'two':
               #self.someFarForP2.join()
           if threadName == 'three':
               #self.someVarForP.join()
               #self.someVarForP2.join()

你们的任何想法都将不胜感激我不会坚持任何特定的方式来做到这一点,而且我对 python 有点陌生,所以欢迎任何建议!

编辑:完整代码

import multiprocessing 
import time 

class test_imports:#Test classes remove 
      def import_1(self, control_queue, thread_number):
          print ("Import_1 number %d started") % thread_number
          run = True
          count = 1
          while run:
                alive = control_queue.get()
                if alive == 't1kill':
                   print ("Killing thread type 1 number %d") % thread_number
                   run = False
                   break
                print ("Thread type 1 number %d run count %d") % (thread_number, count)
                count = count + 1

      def import_2(self, control_queue, thread_number):
          print ("Import_1 number %d started") % thread_number
          run = True
          count = 1
          while run:
                alive = control_queue.get()
                if alive == 't2kill':
                   print ("Killing thread type 2 number %d") % thread_number
                   run = False
                break
                print ("Thread type 2 number %d run count %d") % (thread_number, count)           
                count = count + 1

class worker_manager:
    # ...
    names = {'one': 'import_1', 'two': 'import_2'}
    def __init__(self):
        self.children = {}
    def generate(self, control_queue, threadName, runNum):
        name = self.names[threadName]
        target = i.getattr(name)
        print ("Starting %s number %d") % (name, runNum)
        p = multiprocessing.Process(target=target, args=(control_queue, runNum))
        self.children[threadName] = p
        p.start()
    def terminate(self, threadName):
        self.children[threadName].join()

if __name__ == '__main__':
    # Establish communication queues
    control = multiprocessing.Queue()
    manager = worker_manager()    
    runNum = int(raw_input("Enter a number: ")) 
    threadNum = int(raw_input("Enter number of threads: "))
    threadName = raw_input("Enter number: ")
    thread_Count = 0

    print ("Starting threads") 

    for i in range(threadNum):
        if threadName == 'three':
            manager.generate(control, 'one', i)
            manager.generate(control, 'two', i)
        manager.generate(control, threadName, i)
        thread_Count = thread_Count + 1              
        if threadName == 'three':
            thread_Count = thread_Count + 1 

    time.sleep(runNum)#let threads do their thing

    print ("Terminating threads")     

    for i in range(thread_Count):
        control.put("t1kill")
        control.put("t2kill")
    if threadName == 'three':
        manager.terminate('one')
        manager.terminate('two')
    else:
        manager.terminate(threadName)     

仅编辑worker_manager是实际将要使用的唯一一点。剩下的只是为了开发它只是一个提示。

4

1 回答 1

1

首先,join如果您从一个名为terminate. 当您调用join时,所做的只是让您的父进程等待子进程完成。您仍然需要告诉子进程它需要完成(例如,通过在队列中为它发布一些东西,或向它发送信号),否则您将永远等待。

其次,事实上你已经把self参数从你的方法中去掉了,使用了一个老式的类,在你可能想要一个实例属性的地方创建了一个类属性,并开始谈论看起来非常适合实例的全局变量属性意味着您也可能对类有一些误解。

但最大的问题似乎是您想将字符串名称映射到实例属性(或其他类型的变量)。虽然您可以做到这一点,但您几乎从不想这样做。而不是为每个名称使用单独的属性,只需使用单个dict, 为每个名称指定一个值。例如:

class worker_manager:
    # ...
    def __init__(self):
        self.children = {}
    def generate(self, control_queue, threadName, runNum):
        if threadName == 'one':
            print ("Starting import_1 number %d") % runNum
            p = multiprocessing.Process(target=i.import_1, args=(control_queue, runNum))
            self.children[threadName]
            p.start()
        # ...
    def terminate(self, threadName):
        self.children[threadName].join()

您可以通过分解块的公共部分来进一步清理它if。例如,您可能需要一个调度表。而且,当我们这样做时,让我们使用更多标准名称、4 字符缩进而不是随机缩进、新样式类等:

class WorkerManager(object):
    # ...
    names = {'one': 'import_1', 'two': 'import_2', 'three': 'import_3'}
    def __init__(self):
        self.children = {}
    def generate(self, control_queue, threadName, runNum):
        name = WorkerManager.names[threadName]
        target = i.getattr(name)
        print ("Starting %s number %d") % (name, runNum)
        p = multiprocessing.Process(target=target, args=(control_queue, runNum))
        self.children[threadName] = p
        p.start()
    def terminate(self, threadName):
        self.children[threadName].join()

如果我们可以看到更多您的代码,可能还有很多东西可以重构,但这应该足以让您开始。

于 2013-07-31T18:30:40.890 回答