我用这段代码遇到了奇怪的python行为:
#!/usr/bin/python
import multiprocessing
import time
import sys
class worker(multiprocessing.Process):
def __init__(self, val):
super(worker,self).__init__()
self.val = val
def update_val(self,val):
self.val = val
print("self.val now is %s" %(self.val))
def run(self):
while True:
print("Worker report: val is %s" % (self.val))
time.sleep(self.val)
subproc = worker(10)
subproc.start()
while True:
new_val = sys.stdin.readline().rstrip()
if new_val:
subproc.update_val(new_val)
print("Main report: val is %s" % (subproc.val))
我希望,对象val
中的变量subproc
被update_val
函数改变。但我很惊讶,因为该变量仅针对来自main
流程的查询进行了更改。函数run
仍然使用旧值:
$ ./test.py
Worker report: val is 10
Worker report: val is 10
5
self.val now is 5
Main report: val is 5
Main report: val is 5
Worker report: val is 10
Worker report: val is 10
可能是什么问题?此代码在Python2.7和Python3.6中的工作方式类似。提前致谢!
多处理会产生一个复制当前进程(及其memmory状态)的新进程,因此您无法从当前进程访问该进程,您应该通过它们进行通信。
在进程之间查看sharing state或exchanging objects。
如果您可以使用threading
而不是multiprocessing
,请尝试以下代码。我只是将multiprocessing
更改为threading
并将线程对象的daemon
属性设置为True
。
守护进程
boolean值,指示此线程是否为守护程序线程(True)或不是(False)。必须在调用start()之前设置它,否则引发RuntimeError。它的初始值继承自创建线程;主线程不是守护程序线程,因此在主线程中创建的所有线程都默认为daemon = False。
当没有剩下活着的非守护程序线程时,整个Python程序退出。
简而言之,如果你的worker thread
设置为daemon=True
和main thread
退出,worker thread
也退出,因为没有non-daemon thread
活着(main thread
必须是non-daemon thread
)。
您可以通过KeyboardInterrupt
(Ctrl + c)退出整个程序。
import threading
import time
import sys
class worker(threading.Thread):
def __init__(self, val):
super(worker, self).__init__()
self.val = val
def update_val(self, val):
if val.isdigit():
self.val = int(val)
print("self.val now is %s" % (self.val))
else:
print("val should be digit")
def run(self):
while True:
print("Worker report: val is %s" % (self.val))
time.sleep(self.val)
subproc = worker(10)
subproc.daemon = True # By setting daemon, the threading will be killed when main thread exit.
subproc.start()
while True:
new_val = sys.stdin.readline().rstrip()
if new_val:
subproc.update_val(new_val)
print("Main report: val is %s" % (subproc.val))
工作代码:
#!/usr/bin/python
import multiprocessing
import time
import sys
class worker(multiprocessing.Process):
def __init__(self, valobj):
super(worker,self).__init__()
self.val = valobj
def run(self):
while True:
print("Worker report: val is %s" % (self.val.value))
time.sleep(self.val.value)
valobj = multiprocessing.Value('i', 5)
subproc = worker(valobj)
subproc.start()
while True:
new_val = sys.stdin.readline().rstrip()
if new_val:
valobj.value = int(new_val)
print("Main report: val is %s" %(valobj.value))
此代码具有所需的行为:
$ ./test.py
Worker report: val is 5
1
Main report: val is 1
Main report: val is 1
Main report: val is 1
Worker report: val is 1
Worker report: val is 1
Worker report: val is 1
3
Main report: val is 3
Worker report: val is 3
Worker report: val is 3