所以最近我有以下問題:我必須做一個服務器來處理請求,以便在主進程使用這個值時更新一些值。 所以在這裏,服務器處理函數在子進程中,當我需要時我無法停止它。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
,。有沒有解決方法?