本文介绍了在线程内调用dbus-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在线程内调用dbus方法时出现段错误.这是我的情况:我有一个程序Service1,它公开了方法测试.第二个程序Service2公开一个方法公开.当此方法进行一些认真的数值计算时,我将一些参数从暴露给传递给正在运行的线程读取器.反过来,此线程在结束工作时调用Service1的方法test.我在上次dbus通话中遇到段错误.

I'm getting segfaults when calling a dbus method inside a thread. This is my scenario: I have a program Service1 that exposes a method test. A second program Service2 exposes a method expose. As this method does some serious numerical computation, I pass some params from expose to a running thread reader. This thread, in turn, calls the method test of Service1 when it ends its work. I'm geting segfaults in last dbus call.

代码:

# Service1.py
class Service1(Object):
    def __init__(self, bus):
        name = BusName('com.example.Service1', bus)
        path = '/'
       super(Service1, self).__init__(name, path)

    @method(dbus_interface='com.example.Service1',
        in_signature='s', out_signature='s')
    def test(self, test):
        print 'test being called'
        return test

dbus_loop = DBusGMainLoop()
dsession = SessionBus(mainloop=dbus_loop)
loop = gobject.MainLoop()
gobject.threads_init()

im = Service1(dsession)
loop.run()


# Service2.py
dbus_loop = DBusGMainLoop()
dsession = SessionBus(mainloop=dbus_loop)

class Service2(Object):
def __init__(self, bus):
    name = BusName('com.example.Service2', bus)
    super(Service2, self).__init__(name, '/')

    self.queue = Queue()
    self.db = bus.get_object('com.example.Service1', '/')
    self.dbi = dbus.Interface(self.db, dbus_interface='com.example.Service1')

@method(dbus_interface='com.example.Service2',
        in_signature='', out_signature='')
def expose(self):
    print 'calling expose'
    self.queue.put(('params',))

def reader(self):
    while True:
        val = self.queue.get()
        dd = self.dbi.test('test')
        print dd
        self.queue.task_done()


gobject.threads_init()
loop = gobject.MainLoop()

im = Service2(dsession)
reader = threading.Thread(target=im.reader)
reader.start()

loop.run()

要进行测试,请运行Service1.py,Service2.py,然后再运行此代码段:

To test, run Service1.py, Service2.py and later this snippet:

dbus_loop = DBusGMainLoop()
session = SessionBus(mainloop=dbus_loop)
proxy = session.get_object('com.example.Service2', '/')
test_i = dbus.Interface(proxy, dbus_interface='com.example.Service2')
test_i.expose()

Service2.py在运行几次此代码后应崩溃.但是为什么呢?

Service2.py should crash after running this code a few times. But why?

推荐答案

gobject.threads_init()是不够的,您需要调用dbus.mainloop.glib.threads_init()来使dbus-glib线程安全.

gobject.threads_init() is not enough, you need to call dbus.mainloop.glib.threads_init() to make dbus-glib thread safe.

这篇关于在线程内调用dbus-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 12:35