[systemd-devel] Using eventloop from pthread while using sd-bus functions in main threads causes deadlock or corruption

Lennart Poettering lennart at poettering.net
Tue Jun 7 13:47:08 UTC 2016


On Sun, 05.06.16 13:03, Ben-melech, Shiran (shiran.ben-melech at intel.com) wrote:

> 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.

You have to lock around all functions of sd-event you call.  That
includes sd_event_get_state() and sd_event_get_exit_code().

If you want to unlock the mutex while sd-event is waiting for events,
I'd recommend using sd_event_get_fd() and poll()ing on the returned fd
instead of ever calling sd_event_run() or sd_event_wait().

But the rule is really: if you want to access the same sd_event object
from multiple threads, you have to comprehensively lock around it.

Lennart

-- 
Lennart Poettering, Red Hat


More information about the systemd-devel mailing list