2016-07-31 1 views
0

オブジェクトを作成し、メインスレッドではなくオブジェクトで処理する方法はありますか?私はthis linkを読んだことがありますが、それを私の例に適用する方法を理解していません(下記参照)。PyGObject:スレッドでオブジェクトを操作するには?

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() 

ここで具体的には、私は今取得出力されます:

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

そして、私はそれが多少のようになりたい:

<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 

また私はなりたいです同じスレッドにcls_in_threadが存在することを確認してください(ドキュメントではthreading.local()が見つかりましたが、必要な場合はわかりません)。このような行動を達成する方法はありますか?ここで

答えて

0

はそれを行うための一つの方法の例です:pithos/gobject_worker.py

あなたが別のスレッドにしたいジョブのキューを持っているし、ジョブが完了したら、あなたのコールバックはメインスレッドで呼び出されます。

また、メインスレッドのオブジェクトを別のスレッドから変更しないでください。

関連する問題