DBus python不需要的阻塞线程

时间:2018-01-19 18:43:46

标签: python multithreading dbus

我写了一个简单的dbus服务,它创建了几个线程。但是当服务启动时,所有线程都被阻止了。或多或少这是我的服务:

import time
import threading
import gobject
import dbus
import dbus.service
import dbus.mainloop.glib

dbus.mainloop.glib.threads_init()
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)    

class DummyThread(threading.Thread):
    def __init__(self):
        super(DummyThread, self).__init__()
        self.__running = True

    def run(self):
        while self.__running:
            print "I'm a running thread..."
            time.sleep(1.0)

    def stop(self):
        self.__running = False

class Service(dbus.service.Object):
    def __init__(self):
        super(Service, self).__init__(
            dbus.service.BusName('example.service', bus.SessionBus()),
            '/example/service')
        self.__loop = gobject.MainLoop(is_running=True)

    @dbus.service.method('example.service.Interface')
    def echo(self, data):
        print 'Received: {}'.format(str(data))
        return data

    def run(self):
        self.__loop.run()

    def quit(self):
        if self.__loop.is_running():
            self.__loop.stop()

if __name__ == '__main__':
    service = Service()
    print 'Starting dummy thread...'
    dummy = DummyThread()
    dummy.start()
    print 'Starting echo service...'
    try:
        service.run()
    except KeyboardInterrupt:
        print '\nUser want to quit!'
    print 'Stopping services and threads...'
    dummy.stop()
    dummy.join()
    service.quit()

这也是一个小客户:

import sys
import dbus

class Client(object):
    def __init__(self):
        service = dbus.SessionBus().get_object('example.service',
                                               '/example/service')
        self.echo = service.get_dbus_method('echo', 'example.service.Interface')

if __name__ == '__main__':
    client = Client()
    recv = client.echo(' '.join(sys.argv[1:]))
    print 'Received: {}'.format(recv)

如果您运行服务器,则在任何客户端发出服务请求之前,不会显示该线程的消息。所以我的问题是:是否可以使线程独立于DBus使用的gMainLoop()?

提前谢谢!

0 个答案:

没有答案