Python 如何在类上下文中以方法作为目标启动流程?
我试图在类上下文中启动几个进程,这些进程应该共享一个队列:Python 如何在类上下文中以方法作为目标启动流程?,python,python-3.x,python-multiprocessing,Python,Python 3.x,Python Multiprocessing,我试图在类上下文中启动几个进程,这些进程应该共享一个队列: import multiprocessing import queue class MyMulti: def __init__(self): self.myq = queue.Queue() def printhello(self): print("hello") self.myq.put("hello") def run(self): for
import multiprocessing
import queue
class MyMulti:
def __init__(self):
self.myq = queue.Queue()
def printhello(self):
print("hello")
self.myq.put("hello")
def run(self):
for _ in range(5):
p = multiprocessing.Process(target=self.printhello)
p.start()
if __name__ == "__main__":
multiprocessing.freeze_support()
m = MyMulti()
m.run()
# at that point the queue is being filled in with five elements
这与
C:\Python34\python.exe C:/Users/yop/dev/GetNessusScans/tests/testm.py
Traceback (most recent call last):
File "C:/Users/yop/dev/GetNessusScans/tests/testm.py", line 20, in <module>
m.run()
File "C:/Users/yop/dev/GetNessusScans/tests/testm.py", line 15, in run
p.start()
File "C:\Python34\lib\multiprocessing\process.py", line 105, in start
self._popen = self._Popen(self)
File "C:\Python34\lib\multiprocessing\context.py", line 212, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Python34\lib\multiprocessing\context.py", line 313, in _Popen
return Popen(process_obj)
File "C:\Python34\lib\multiprocessing\popen_spawn_win32.py", line 66, in __init__
reduction.dump(process_obj, to_child)
File "C:\Python34\lib\multiprocessing\reduction.py", line 59, in dump
ForkingPickler(file, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <class '_thread.lock'>: attribute lookup lock on _thread failed
不过,这也会以同样的方式崩溃
有没有办法以方法作为目标启动进程?我应该使用
self.myq=multiprocessing.Queue()
而不是Queue.Queue()
除了queue.queue()
,是进程安全的
我暂时没有回答这个问题,如果整个方法是错误的,可能会有人评论。如果我记得,你需要调用m.start()而不是m.run()。
。run()
是我的类MyMulti
的一个方法。我的盲症占了上风。
import multiprocessing
import queue
def work(foo):
foo.printhello()
class MyMulti:
def __init__(self):
self.myq = queue.Queue()
def printhello(self):
print("hello")
self.myq.put("hello")
def run(self):
for _ in range(5):
p = multiprocessing.Process(target=work, args=(self,))
p.start()
if __name__ == "__main__":
multiprocessing.freeze_support()
m = MyMulti()
m.run()
# at that point the queue is being filled in with five elements