Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 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 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...