Subject: Re: bug#36609: 27.0.50; Possible race-condition in threading implementation

From: Eli Zaretskii <[email-masked]>
Date: Fri, 12 Jul 2019 22:57:05 +0300

> From: Pip Cet <[email-masked]>
> Date: Fri, 12 Jul 2019 19:24:38 +0000
> Cc: [email-masked], [email-masked]
> 
> I'm now convinced that there simply is no safe way to call select()
> from two threads at once when using glib.

I hope not, although GTK with its idiosyncrasies caused a lot of pain
for the threads implementation in Emacs.

> I think our options are hacking around it and hoping nothing breaks
> (this is what the attached patch does; it releases the main context
> glib lock from the wrong thread soon "after" the other thread called
> select, but there's actually no way to ensure that "after" is
> accurate), or rewriting things so we have a single thread that does
> all the select()ing.

Hmm... how would this work with your patch?  Suppose one thread calls
xg_select, acquires the Glib lock, sets its holding_glib_lock flag,
then releases the global Lisp lock and calls pselect.  Since the
global Lisp lock is now up for grabs, some other Lisp thread can
acquire it and start running.  If that other thread then calls
xg_select, it will hang forever trying to acquire the Glib lock,
because the first thread that holds it is stuck in pselect.

Am I missing something?

I know very little about GTK and the Glib context lock, but AFAIR we
really must treat that lock as a global one, not a thread-local one.
So I think it's okay for one thread to take the Glib lock, and another
to release it, because Glib just wants to know whether the "rest of
the program" has it, it doesn't care which thread is that which holds
the lock.