Python&PyGTK: Transport data to threading

血红的双手。 提交于 2019-12-11 09:16:26

问题


I would like to transfer data to threading class, but I can't get what is wrong. The code below is from this question and I changed it a little.

This is a code:

import gtk, gobject, threading, time

gobject.threads_init()

class T(threading.Thread):
    pause = threading.Event()
    stop = False

    def start(self, data, *args):
        super(T, self).start()

    def run(self, data):
        while not self.stop:
            self.pause.wait()
            gobject.idle_add(lambda *a : self.rungui(data))
            time.sleep(0.1)

    def rungui(self, data):
        print "printed"
        print data

thread = T()

class Start:

        def toggle_thread(self, data=None, *args):
                if not thread.is_alive():
                    thread.start(data)
                    thread.pause.set()
                    self.button.set_label('Pause Thread')
                    return

                if thread.pause.is_set():
                    thread.pause.clear()
                    self.button.set_label('Resume Thread')
                else:
                    thread.pause.set()
                    self.button.set_label('Pause Thread')

        def __init__(self):
                thread = T()
                window = gtk.Window()
                self.button = gtk.ToggleButton('Start Thread')
                data = 3
                self.button.connect('toggled', lambda *a : self.start(data), None)
                window.add(self.button)
                self.button.show()
                window.show()

        def start(self, data=None):
                self.toggle_thread(data)

        def main(self):
                gtk.main()

if __name__ == "__main__":
        start = Start()
        start.main()

What do I have to correct to get threading fully working?


回答1:


Don`t work with gtk out of gui thread. That about:

gobject.idle_add(self.rungui)

Example at your link work fine, but need system kill command for termination. And super() can`t bring arguments to run() function.

My threads initialization looks like this:

class VirtService(threading.Thread):
        def __init__(self, queue):
                threading.Thread.__init__(self)
                self.queue = queue

        def thread_loop(self):
                while self.queue.qsize():
                        data_command = self.queue_get()

...

queue = Queue()

if __name__ == '__main__':
        gobject.threads_init()
        vs = VirtService(queue)

And you may use Queue for data translation to both directions. You may use also queue for command. In non-graphical thread create c++ poll() analog through Queue.qet(), and in gui thread queue.put()



来源:https://stackoverflow.com/questions/13122984/pythonpygtk-transport-data-to-threading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!