Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

multithreading - Threading in Gtk python

So I'm busy writing an application that needs to check for updates from a website after a certain amount ouf time, I'm using python with Gtk +3

main.py file

class Gui:
    ...
    def on_update_click():
        update()

app=Gui()
Gtk.main()

update.py file

def update():
    #check site for updates
    time.sleep(21600) #check again in 6hrs

I suspect I'll have to use threading. my thinking is:

Gtk.main() runs the main thread.

when the user clicks the update button, update() runs in the background. #thread 2

Is my thinking correct or have I missed something?

EDIT: Ok,
on_update_click function:

            Thread(target=update).start(). 

K, computer does not freeze anymore :D

so what happens now is that only when I close Gtk.main() does the update thread only start. It's good that is continues to update when the UI is closed, but i'd also like it to start when the UI is up.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So I finally managed to get it to work. I needed to say:

from gi.repository import Gtk,GObject

GObject.threads_init()
Class Gui:
    .....
    ......
    def on_update_click():
            Thread(target=update).start()

At first I used:

thread.start_new_thread(update())

in the on_update_click function. As mentioned my J.F Sebastian this was incorrect as this would immediately call this thread. This froze my whole computer.

I then just added:

Thread(target=update).start()

The on_update_clicked function only worked once the main Thread Gtk.main() was closed. So the threads were not running simultaneously.

by adding: GObject.threads_init()

this allowed for the threads to run serially to the python interpreter: Threads in Gtk!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...