在线程内调用 dbus 方法时出现段错误。这是我的场景:我有一个公开方法测试的程序 Service1。第二个程序 Service2 公开了一个方法 expose。由于此方法进行了一些严肃的数值计算,我将一些参数从 expose 传递给正在运行的线程读取器。该线程在结束其工作时依次调用 Service1 的方法测试。我在上次 dbus 调用中遇到段错误。
代码:
# 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 和稍后的代码片段:
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 在运行此代码几次后应该会崩溃。但是为什么?
最佳答案
gobject.threads_init()
是不够的,你需要调用dbus.mainloop.glib.threads_init()
使dbus-glib线程安全。
关于python - 在线程内调用 dbus-python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6379553/