[英]Calling dbus-python inside a thread
我在線程中調用dbus方法時遇到段錯誤。 這是我的場景:我有一個程序Service1公開方法測試。 第二個程序Service2公開了一個方法公開。 由於這個方法做了一些嚴肅的數值計算,我將一些params從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線程安全。
在Service1.py
,嘗試在將dbus_loop
分配給dbus_loop
gobject.threads_init()
之前調用gobject.threads_init()
DBusGMainLoop()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.