Subject: bug#64819: 30.0.50; condition-wait not interruptible

From: Helmut Eller <[email-masked]>
Date: Mon, 24 Jul 2023 16:57:05 +0200

On Mon, Jul 24 2023, Eli Zaretskii wrote:

>> From: Helmut Eller <[email-masked]>
>> We could say that C-g sets quit-flag and causes all blocking calls to
>> condition-wait to return nil (spurious wakeup).  At that point all
>> threads are conceptually running.  Then the first thread (unspecified
>> which one) who calls maybe_quit() finishes handling C-g and clears
>> quit-flag afterwards.  Those threads who don't feel prepared to handle
>> C-g can bind inhibit-quit.
>
> I don't think we can allow more than one thread at a time to run the
> parts of the Lisp interpreter that lead to maybe_quit.

I didn't suggest that.  Nor did I suggest that the thread scheduler
should switch away from the currently running thread.

What I did suggest is that the thread blocked in condition-wait is
considered runnable.  So that the thread scheduler is allowed to pick
this thread the next time when somebody calls thread-yield or
condition-wait.

To the thread it will look like a spurious wakeup (i.e. condition-wait
returned but the condition isn't actually true) but Lisp code must
already be prepared for such a situation.

The bytecode interpreter calls maybe_quit before every call or backward
branch, so maybe_quit will be called very soon after the spurious
wakeup.

> Also, I don't think what you describe, even if it were possible, is
> what users expect: they expect that the thread which is running is
> interrupted, and either exits or handles the quit, and all the other
> threads still wait for the condition var.

Maybe we can agree on this: when only one thread exists and it is
blocked in condition-wait, then condition-wait should be interruptible
by C-g.

For the situation where some threads are blocked in condition-wait and
one other thread is running, I think that running thread would call
maybe_quit and clear quite-flag before calling thread-yield.  The other
threads would observe spurious wakeups as soon as they are allowed to
run.

> So I think to do anything smarter in the deadlock situation you
> describe we'd need to detect the deadlock first.  Once we do that
> (which isn't easy: perhaps do that in the signal handler?), we'd need
> to decide which of the deadlocked threads to free, which is also not
> trivial.  Hmmm...

I doubt that deadlock detection is possible in the general case.
E.g. how could we possibly know that a timer is or isn't going to call
condition-notify in 5 seconds?

> Btw, did you try your recipe in a Unix TTY?  There, C-g actually
> delivers SIGINT to Emacs, so you might see a different behavior (or a
> crash ;-).

When I run the recipe with: "emacs -nw -l deadlock.el -f deadlock" then
I see the emergency escape feature kick in.  Only after the second C-g
(of course).  A single C-g doesn't seem to do anything.

Helmut