在python-multiprocessing中对象之间的通信和比较?

时间:2015-02-26 15:59:35

标签: python parallel-processing multiprocessing

我试图找到一种方法来比较不同对象(继承自Thread类),以保持parallilsm(实时处理)。

每个工人都有三个字段(message,count,n)。我每次都在更新Count。让我们说我有三个帖子workers。我需要在我的服务器中根据字段count进行比较,如何在每个工作人员Worker.count之间进行访问和比较,以保持并行性

from Queue import Queue
from threading import Thread

import time

class Worker(Thread):

    def __init__(self, message, n):
        Thread.__init__(self)
        self.message = message
        self.count= 0
        self.n = n

    def run(self):
        while True:
            print(self.message)
            self.count+=1
            time.sleep(self.n)

class Comparator(Thread):

    def __init__(self, message, n):
        Thread.__init__(self)
        self.message = message
        self.n = n

    def run(self):
        while True:
            max= max([x.count for x in threads]) # how can I access to other threads 
            print  "max", max
            time.sleep(self.n)



thread1 = Worker("Test-1", 1)
thread2 = Worker("Test-2", 3)


s = Comparator("Test-3", 2)

s.start()
s.join()

threads = [thread1, thread2]

for g in threads:
    g.start()

for worker in threads:
      # wait for workers
      worker.join()

注意这里使用共享对象对我来说不是一个好的解决方案,例如使用Queue()不是我想要的,我需要根据我更新的对象中的更新字段进行比较在旅途中(为简单起见,我使用max())。

1 个答案:

答案 0 :(得分:-1)

您可以将threads列表传递给Comparator __init__()方法:

[...]
class Comparator(Thread):

    def __init__(self, message, n, threads):
        Thread.__init__(self)
        self.threads = threads

    def run(self):
        while True:
            max= max([x.count for x in self.threads]) 
            print("max", max)
            time.sleep(self.n)

[...]
threads = [thread1, thread2]
s = Comparator("Test-3", 2, threads)