我試圖對我爲我的工作所做的程序實現多重處理,並且遇到了問題。請參閱下面的簡化代碼;當我啓動一個進程時,它啓動了另一個gui實例;當我關閉該實例時,會處理cpu_intensive函數。這是我第一次使用的Tkinter和線程和進程,以便有可能是在那裏;-)感謝您尋找到這不止一個問題:產卵過程啓動Tkinter的另一個實例 - Python 2
from Tkinter import *
from threading import Thread
from multiprocessing import Process, Queue
source_queue = Queue()
def thread_launch():
"""launches a thread to keep the gui responsive"""
thread1 = Thread(target=process_engine)
return thread1.start()
def process_engine():
"""spawns processes and populates the queue"""
p1 = Process(target=cpu_intensive, args=(source_queue,))
p1.start()
p2 = Process(target=cpu_intensive, args=(source_queue,))
p2.start()
for i in range(10):
source_queue.put(i)
print "Added item", i, "to queue"
source_queue.close()
source_queue.join_thread()
p1.join()
p2.join()
def cpu_intensive(item_toprocess):
"""function to be multiprocessed"""
print "Processed: item", item_toprocess.get()
class Application:
def __init__(self, master):
"""defines the gui"""
self.master = master
self.process_button = Button(self.master,
text="Process",
command=thread_launch)
self.process_button.pack(padx=100, pady=100)
def __main__():
"""launches the program"""
root = Tk()
app = Application(root)
root.mainloop()
if __name__ == __main__():
__main__()
嘗試: 'if __name__ ==「__main __」:' 改爲。 – cdarke
它的工作原理當然更有意義!謝謝:-) –
已作爲解答已添加 – cdarke