在PyGTK中,如何启动线程并仅在线程终止时继续调用函数

In PyGTK, how to start thread and continue calling function only when thread terminates

阅读了很多关于线程和 .join() 函数的问题后,我仍然找不到如何调整基本 pygobject threads example from documentation,使其符合我的用例:

#!/bin/python3

import threading
import time
from gi.repository import GLib, Gtk, GObject

def app_main():
    win = Gtk.Window(default_height=50, default_width=300)
    win.connect("destroy", Gtk.main_quit)

    def update_progess(i):
        progress.pulse()
        progress.set_text(str(i))
        return False

    def example_target():
        for i in range(50):
            GLib.idle_add(update_progess, i)
            time.sleep(0.2)

    def start_actions(self):
        print("do a few thing before thread starts")
        thread = threading.Thread(target=example_target)
        thread.daemon = True
        thread.start()
        print("do other things after thread finished")

    mainBox = Gtk.Box(spacing=20, orientation="vertical")
    win.add(mainBox)
    btn = Gtk.Button(label="start actions")
    btn.connect("clicked", start_actions)
    mainBox.pack_start(btn, False, False, 0)
    progress = Gtk.ProgressBar(show_text=True)
    mainBox.pack_start(progress, False, False, 0)
    win.show_all()


if __name__ == "__main__":
    app_main()
    Gtk.main()

如何使此代码仅在我的线程终止且不冻结 main window 后打印 "do other things after thread finished"

首先,为了清楚起见,线程在您调用其 start 方法后并未完成。

查看线程中代码运行的定义:

def example_target():
    for i in range(50):
        GLib.idle_add(update_progess, i)
        time.sleep(0.2)

这基本上是重复以下 50 次:

  • 告诉 GTK 在下次系统空闲(没有事件要处理)时执行 update_progress
  • 睡眠 0.2 秒。

您可以定义一个函数 after_thread,并在线程完成时安排该函数:

def example_target():
    for i in range(50):
        GLib.idle_add(update_progess, i)
        time.sleep(0.2)
    # loop is finished, thread will end.
    GLib.idle_add(after_thread)