简体   繁体   English

在python多处理中的对象之间进行通信和比较?

[英]Communicating and comparing between objects in python-multiprocessing?

I am trying to find a way to compare between different objects (inherited from Thread class) in a way that keep parallilsm (real-time processing). 我试图找到一种方法来比较不同的对象(从Thread类继承),以保持平行(实时处理)。

Every worker has three fields (message, count, n ). 每个工人都有三个字段(message,count,n)。 I am updating Count everytime. 我每次都在更新Count Let's say that I have three threads workers . 假设我有三个线程workers I need to compare in my server based on the field count , how can I do access and compare between Worker.count of every worker, in a way that I keep parallelism 我需要基于字段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()

NOTE Using shared object here is not a good solution for me, using Queue() for example is not what I want, I need to do comparision based on updated field in the object that I update on the go (for simplicity, I use max() ). 注意在这里使用共享对象对我来说不是一个好的解决方案,例如,使用Queue()并不是我想要的,我需要根据在旅途中更新的对象中的更新字段进行比较(为简单起见,我使用max ())。

you can pass the threads list to Comparator __init__() method : 您可以将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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM