简体   繁体   中英

Running multiple loops simultaneously

I am trying to run 2 loops at the same time using multiprocessing, but they only seem to run sequentially. 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. 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.

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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