Frage

I'm playing with DBus and python. I have created a very simple DBus client and corresponding server. It works perfectly when each runs on its own python process.

However, I'm trying to get it to work in the same process, but it only works 10% of the times I run the code. The rest of time, it simply freezes.

I've simplified the code as much as possible, and the problem persists. The code is below:

from threading import Thread
import gobject
import dbus
import dbus.service
import dbus.mainloop.glib

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

objname="com.visualtools.venom.MockService"
objpath="/" + objname.replace(".","/")

class ExampleApi(dbus.service.Object):
    def __init__(self):
        dbus.service.Object.__init__(self, dbus.service.BusName(objname, dbus.SystemBus()), objpath)
    @dbus.service.method(objname, out_signature='s')
    def ping(self, msg):
        return "Message is: %s" %msg

def client():
    while not loop.is_running():
        continue
    api = dbus.Interface(dbus.SystemBus().get_object(objname, objpath), objname)
    print "calling api..."
    result = api.ping("i'm the client")
    print "api result is: %s" %result
    loop.quit()

loop = gobject.MainLoop()
server = ExampleApi()
Thread(target=client).start()
loop.run()

Just copy&paste into a file, and run it 10 times. I can reproduce the problem in debian sid and debian squeeze.

What am I doing wrong?

War es hilfreich?

Lösung

Using threads is probably the problem. Simon McVittie said in dbus ML:

It is unclear whether the dbus-glib main loop glue (as set up by DBusGMainLoop) is thread-safe or not. The safest assumption is always "if you don't know whether foo is thread-safe, it probably isn't". In any case, if it is thread-safe, the subset of it that's exposed through dbus-python isn't enough to use it in multiple threads.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top