2015-11-08 117 views
1

我想使用多處理同時運行2個循環,但它們似乎只能按順序運行。 當第一個循環啓動tkinter的mainloop()進程時,另一個循環在GUI窗口關閉之前不會啓動,然後計數循環開始。 我試過多線程和多處理結果相同。我需要他們同時運行。下面是一個演示問題的簡單示例。我使用python 2.7.10。同時運行多個循環

from multiprocessing import Process 
from Tkinter import * 
import time 



count = 0 

def counting(): 
    while True: 
     global count 
     count = count + 1 
     print count 
     time.sleep(1) 

class App(): 

    def __init__(self): 
     self.myGUI = Tk() 
     self.myGUI.geometry('800x600') 

     self.labelVar = StringVar() 
     self.labelVar.set("test") 

     self.label1 = Label(self.myGUI, textvariable=self.labelVar) 
     self.label1.grid(row=0, column=0) 


app = App() 

t1 = Process(target = app.myGUI.mainloop()) 
t2 = Process(target = counting()) 

t1.start() 
t2.start() 

回答

6

您正在調用函數並等待它們完成,以便將它們的結果作爲進程目標傳遞。傳函數本身代替 - 那就是,改變這種:

t1 = Process(target = app.myGUI.mainloop()) 
t2 = Process(target = counting()) 

這樣:

t1 = Process(target=app.myGUI.mainloop) 
t2 = Process(target=counting) 

因此該方法可以調用(在子進程)的功能。

+0

我試着改變上面的代碼,並導致一個很大的錯誤。將t1.start()更改爲t1.run()工作,但它仍然按順序運行。 –

+0

運行時錯誤:嘗試在當前進程完成引導階段之前啓動新進程。 –