[systemd-devel] Using eventloop from pthread while using sd-bus functions in main threads causes deadlock or corruption
Ben-melech, Shiran
shiran.ben-melech at intel.com
Sun Jun 5 13:03:22 UTC 2016
On Wed, 2016-06-01 at 15:45 +0200, Lennart Poettering wrote:
> On Wed, 01.06.16 13:33, Ben-melech, Shiran (
> shiran.ben-melech at intel.com) wrote:
> > > Hi,
> >
> > i'm writing a small C library using sd-bus to communicate with
> > bluetooth low energy devices.
> >
> > Instead of using a loop for reading from a specific characteristic
> > on
> > the ble device, I want to use eventloop and register for value
> > changes
> > on the object that represent this characteristic.
> >
> > When i run the eventloop in a different pthread, since on the main
> > i'm
> > writing to the ble service to get the data i want from the
> > characteristic - i get either what seems to be a deadlock or seg
> > faults.
> >
> > i've used the example on your blog (
> > http://0pointer.net/blog/introducing-sd-event.html) to set up the
> > event.
> >
> > Can anyone please advise? what might i be doing wrong?
> > sd-event is not thread-safe, but it is threads-aware. That means it
> won't do any locking on its own, but it will work fine in a threaded
> environment as long as you use the same sd_event object (and its
> auxiliary objects, i.e. sd_event_source) only from within one thread.
> > In other words: as long as your don't "reach over" from one thread to
> the other to access sd-event objects you should be safe. If you do,
> then you need to wrap things in your own locking to ensure you never
> end up accessing the same sd-event (or any of its auxiliary
> sd_event_source objects) from multiple threads at the same time.
> > Lennart
Hi,
I've added mutex locks over all the sd functions using the bus as well
as around the event loop.
This is how i run the event loop inside the pthread:
while (sd_event_get_state(event) != SD_EVENT_FINISHED) {
pthread_mutex_lock (&lock);
sd_event_run(event, 1000);
pthread_mutex_unlock (&lock);
if (r < 0) {
sd_eve
nt_get_exit_code(event, &r);
syslog(LOG_ERR, "%s: Error
sd_event_run with code %d", __FUNCTION__, r);
return NULL;
}
sched_yield();
}
This did solve the seg faults and deadlocks but the callbacks are missed and never called. In addition the execution is extremely slow since the event loop is catching the lock most of the time.
Any suggestions?
Regards,
Shiran
---------------------------------------------------------------------
Intel Electronics Ltd.
This e-mail and any attachments may contain confidential material for
the sole use of the intended recipient(s). Any review or distribution
by others is strictly prohibited. If you are not the intended
recipient, please contact the sender and delete all copies.
More information about the systemd-devel
mailing list