0

Is there a way to create objects and work with them not in the main thread? I've read this link, but don't understand how to apply it to my example (see below).

import threading

from gi.repository import Gtk, Gdk, GObject, GLib


class Foo:

    def bar(self):
        pass


class ListeningThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.cls_in_thread = None

    def foo(self, _):
        self.cls_in_thread = Foo()
        print(threading.current_thread())
        print('Instance created')

    def bar(self, _):
        self.cls_in_thread.bar()
        print(threading.current_thread())
        print('Instance method called')

    def run(self):
        print(threading.current_thread())


def main_quit(_):
    Gtk.main_quit()


if __name__ == '__main__':
    GObject.threads_init()

    window = Gtk.Window()
    box = Gtk.Box(spacing=6)
    window.add(box)

    lt = ListeningThread()
    lt.daemon = True
    lt.start()
    button = Gtk.Button.new_with_label("Create instance in thread")
    button.connect("clicked", lt.foo)

    button2 = Gtk.Button.new_with_label("Call instance method in thread")
    button2.connect("clicked", lt.bar)

    box.pack_start(button, True, True, 0)
    box.pack_start(button2, True, True, 0)

    window.show_all()
    window.connect('destroy', main_quit)

    print(threading.current_thread())
    Gtk.main()

To be more precise here is the output I get now:

<ListeningThread(Thread-1, started daemon 28268)>
<_MainThread(MainThread, started 23644)>
<_MainThread(MainThread, started 23644)>
Instance created
<_MainThread(MainThread, started 23644)>
Instance method called

And I would like it to be somewhat like this:

<ListeningThread(Thread-1, started daemon 28268)>
<_MainThread(MainThread, started 23644)>
<ListeningThread(Thread-1, started daemon 28268)>
Instance created
<ListeningThread(Thread-1, started daemon 28268)>
Instance method called

Moreover I would like to be sure that cls_in_thread exists in that same thread (In docs I've found threading.local(), but I'm not sure if it's needed). Is there a way to achieve such behaviour?

1 Answers1

0

Here is an example of one way to do it: pithos/gobject_worker.py

You have a Queue of jobs you want on another thread and then your callback is called on the main thread once the job is done.

Also do realize you should not be modifying objects on the main thread from another thread.

TingPing
  • 2,129
  • 1
  • 12
  • 15