所以最近我有以下问题:我必须做一个服务器来处理请求,以便在主进程使用这个值时更新一些值。 所以在这里,服务器处理函数在子进程中,当我需要时我无法停止它。threading.Thread against multiprocessing.Process
为了测试什么threading.Thread
或multiprocessing.Process
之间我的问题的最佳解决方案,我做了这个小程序如下:
import multiprocessing
import time
import threading
class SubProcess(multiprocessing.Process):
def __init__(self, source):
self.source = source
super(SubProcess, self).__init__()
def run(self):
while 1:
time.sleep(1) # Waiting for request...
self.source.somevar["anotherkey"].append(5)
print "My subprocess : ", id(self.source), id(self.source.somevar), self.source.somevar
class SubThread(threading.Thread):
def __init__(self, source):
self.source = source
super(SubThread, self).__init__()
def run(self):
while 1:
time.sleep(1) # Waiting for request...
self.source.somevar["anotherkey"].append(5)
print "My subthread : ", id(self.source), id(self.source.somevar), self.source.somevar
class Source:
def __init__(self):
self.somevar = {"akey": "THE key", "anotherkey": [5]}
def start_process(self):
self.process = SubProcess(self)
self.process.start()
def stop_process(self):
self.process.terminate()
def start_thread(self):
self.thread = SubThread(self)
self.thread.start()
def stop_thread(self):
# self.thread.stop() # What the hell should i put here
pass
s = Source()
s.start_process()
time.sleep(2)
print "End : ", id(s), id(s.somevar), s.somevar
s.stop_process()
s.start_thread()
time.sleep(2)
print "End : ", id(s), id(s.somevar), s.somevar
s.stop_thread() # Obviously, thread never ends...
所以threading.Thread
修改原始s.somevar
但我不能阻止它,而multiprocessing.Process
不会修改原始s.somevar
,但我可以阻止它。
我正在寻找一个解决方案,我可以停止线程(用SIGTERM),并在该线程可以修改使用标准库原班Source
,。有没有解决方法?