python - 同时运行多个循环

标签 python multiprocessing

我正在尝试使用多处理同时运行 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()

最佳答案

您正在调用函数,并等待它们完成,以便将它们的结果作为 Process 目标传递。而是传递函数本身 - 也就是说,改变这个:

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

为此:

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

以便进程可以调用这些函数(在子进程中)。

关于python - 同时运行多个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33591675/

相关文章:

python - 是否可以同时执行两个函数

Python 多处理 : sharing data between processes

python - 如何创建一个包含 python 对象的所有字段和属性的字典?

python - 无法使用 Python/opencv : Device or resource busy 关闭/打开 CameraCapture

multithreading - 如何在 Perl 中实现信号量线程通信?

python - 跨多个进程使用双端队列对象

Python multiprocessing.Process 行为不确定

python - 将 tastypie 导入到项目中

python - 如何在 Python 中比较两条 3D 曲线?

Python RoboBrowser SSL 错误 : bad handshake: SysCallError(104, 'ECONNRESET' )