Dbus in Multi-threaded application
Thiago Macieira
thiago at kde.org
Sun Aug 27 17:32:24 UTC 2017
On Sunday, 27 August 2017 02:52:21 PDT Abhi Arora wrote:
> Hello Community,
>
>
> I have developed an application for BLE using DBUS for Linux. It is working
> fine but sometimes I have seen seg fault.
Using libdbus-1?
Be VERY careful about threading, then. The recommendation is to leave all the
D-Bus messaging to a single thread.
> My application has a single event loop thread for dbus (THREAD A). I have
> used glib event loop. It is exactly similar to "bluetoothctl" event loop
> implementation:
> https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/gdbus/mainloop.c .
> I using that thread for receiving signal and error dbus messages using
> filter callbacks (by using function "dbus_connection_add_filter"). I have
> set watch and timeout handlers using glib implementation (by calling
> dbus_connection_set_watch_functions, dbus_connection_set_timeout_functions
> and dbus_connection_set_dispatch_status_function). You can check the above
> link as i have using their code.
So far, so good. One thread doing the D-Bus work.
> My main thread (THREAD B) calls dbus methods and block on pending call
> instance for replies.
Mistake found. Calling those D-Bus methods will cause libdbus-1 to call your
callbacks to set timeouts and watches. And they will be called in the thread
that you called dbus_connection_send_with_reply_and_block on, not the thread
that is handling the D-Bus connection.
I don't know how Glib deals with your g_source_remove and family being called
on a GMainLoop outside of the thread where that main loop is running. That's
up to you to find out. Also note that dbus_connection_send_with_reply_and_block
may call your set dispatch_status function from the main thread too., so how
does your queue_dispatch function react to being called from that thread?
My suggestion: do NOT call dbus_connection_* from the main thread. Call it
only from the thread you started to handle the D-Bus connection in the first
place. That's the architecture that both GDBus and QtDBus have.
> For example, THREAD B calls a dbus method and it has set a timeout for it. I
> will then block on it. The THREAD A may dispatch a timeout event if timeout
> has occurred. I am not completely sure but I think there could be some race
> condition in this case. Please help me.
Yes, that can happen too. My suggestion fixes this.
--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
Software Architect - Intel Open Source Technology Center
More information about the dbus
mailing list