2015-11-18 37 views
0

我試圖對我爲我的工作所做的程序實現多重處理,並且遇到了問題。請參閱下面的簡化代碼;當我啓動一個進程時,它啓動了另一個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__() 
+0

嘗試: 'if __name__ ==「__main __」:' 改爲。 – cdarke

+0

它的工作原理當然更有意義!謝謝:-) –

+0

已作爲解答已添加 – cdarke

回答

0

嘗試:

if __name__ == "__main__": 

代替。以前的版本調用main,但檢查返回的值(在這種情況下爲None)。問題是(我懷疑你在Windows上)子進程也在if聲明中調用main

+0

已確認,我在Windows上。再次感謝,因爲這個,我花了很多時間重寫我的代碼;-) –

+0

'main'的問題發生在Windows上,因爲Windows沒有以與UNIX/Linux的確如此。所以當'multiprocessing'創建一個子時,它會再次運行'main'。 – cdarke

+0

感謝您的解釋,很高興終於明白髮生了什麼。 –