简体   繁体   English

同时运行多个循环

[英]Running multiple loops simultaneously

I am trying to run 2 loops at the same time using multiprocessing, but they only seem to run sequentially. 我正在尝试使用多处理程序同时运行2个循环,但它们似乎只按顺序运行。 When the first loop starts the mainloop() process for tkinter the other loop doesn't start until the GUI window is shut down, then the count loop starts. 当第一个循环启动tkinter的mainloop()进程时,另一个循环直到GUI窗口关闭才开始,然后开始计数循环。 I have tried multithreading and multiprocessing with the same result. 我尝试了多线程和多处理的结果相同。 I need them to run concurrently. 我需要它们同时运行。 Below is a simple example that demonstrates the problem. 下面是一个简单的示例,演示了此问题。 I'm Using python 2.7.10. 我正在使用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()

You are calling the functions, and waiting for them to finish, in order to pass their result as the Process target. 您正在调用函数,并等待它们完成,以便将其结果作为Process目标传递。 Pass the functions themselves instead - that is, change this: 而是自己传递函数 -即更改此值:

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

to this: 对此:

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

So that the Process can call those functions (in a subprocess). 这样,流程可以调用这些函数(在子流程中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM