我正在尝试对我为我的工作制作的程序实施多处理,而且我遇到了问题。请参阅下面的简化代码;当我启动一个进程时,它会启动另一个gui实例;当我关闭该实例时,处理cpu_intensive函数。这是我第一次使用Tkinter和线程和进程,因此可能存在多个问题;-)感谢您对此进行调查:
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__()
答案 0 :(得分:0)
尝试:
if __name__ == "__main__":
代替。以前的版本调用main但检查返回值(在这种情况下为None
)。问题是(我怀疑你在Windows上),子进程也在main
语句中调用if
。