无法启动多进程线程并使用事件

时间:2016-10-21 17:15:41

标签: python multithreading events multiprocess

我正在尝试将事件和队列都提供给我的工作线程。队列是让他们彼此交谈,事件是用来发信号通知他们在需要时停止工作。我一直收到这个错误,我无法弄清楚我的定义构造函数

有什么问题

这是错误:

 Traceback (most recent call last):
   File "dualThreaded.py", line 52, in <module>
    c = get_Count(q, e)
 TypeError: __init__() takes exactly 2 arguments (3 given)

这是我的代码:

 from Queue import Empty
 from multiprocessing import Process, Queue, Event 
 import time

 class get_Count(object):
     def __init__(self, q): 
         self.q = q 

     def run(self, e):
         i = 0
     run = True
         while run == True:
             print 'putting' 
             self.q.put('foo %d' % i ) 
             time.sleep(.5)
          if e.is_set():
             run = False

class read_Count(object):
     def __init__(self, q):
         self.q = q 

     def run(self, e):
         while True:
             try:
                value =  self.q.get(False)
                print value

             except Empty:
                 print 'Nothing to process atm'
                 e.set()
             time.sleep(.2)



 if __name__ == '__main__':

     e = Event()
     q = Queue()
     c = get_Count(q, e)
     l = read_Count(q, e)

     p1 = Process(target=c.run)
     p1.start()

     p2 = Process(target=l.run)
     p2.start()

     p1.join()
     p2.join()

编辑固定拼写错误:

1 个答案:

答案 0 :(得分:0)

暂时忽略不准确的堆栈帧,请考虑c = get_Count(q, e)get_Count的初始值设定项def __init__(self, q):在强制self之后只接受一个参数,但您用两个参数调用它。我已更新您的代码以在初始化程序中包含e并进行一些小的清理。它有点运行,但你可能需要解决下一个问题。

from Queue import Empty
from multiprocessing import Process, Queue, Event 
import time

class get_Count(object):
    def __init__(self, q, e): 
        self.q = q
        self.e = e

    def run(self):
        i = 0
        run = True
        while run == True:
            print 'putting' 
            self.q.put('foo %d' % i ) 
            time.sleep(.5)
            if self.e.is_set():
                run = False

class read_Count(object):
    def __init__(self, q, e):
        self.q = q
        self.e = e

    def run(self):
        while True:
            try:
                value =  self.q.get(False)
                print value

            except Empty:
                print 'Nothing to process atm'
                self.e.set()
            time.sleep(.2)


if __name__ == '__main__':

     e = Event()
     q = Queue()
     c = get_Count(q, e)
     l = read_Count(q, e)

     p1 = Process(target=c.run)
     p1.start()

     p2 = Process(target=l.run)
     p2.start()