Subject: Re: bug#73131: 28.2; Yielded threads get killed on C-g

From: Eli Zaretskii <[email-masked]>
Date: Mon, 09 Sep 2024 15:22:48 +0300

> From: Swapneil Singh <[email-masked]>
> Date: Sun, 8 Sep 2024 12:08:00 -0400
> 
> When using the Emacs cooperative threading system in a new project, I
> noticed that calling C-g results in quitting the background thread I
> create, even when those threads are yielded.
> 
> Sending this as a bug report per Eli Zaretskii's mention that it may not
> be expected behavior
> (https://www.reddit.com/r/emacs/comments/1fbkkii/comment/lm3boja/).
> 
> Repro recipe:
> - emacs -Q
> - `C-x 3` and run `list-threads` in the new window, then return to the
> older window
> - `M-:` `(make-thread (lambda () (cl-loop while t do (progn
> (thread-yield) (sleep-for 30)))))` and wait for the new thread to yield to
> the main thread.
> - `C-g`. The new thread disappears from the `list-threads` window.
> 
> 
> Note: While I am admittedly on Windows, given this behavior is within the
> cooperative threads of the Emacs runtime (rather than actual Windows
> threads) I *really* doubt that has anything to do with it.

Actually, your being on MS-Windows does explain what you see, because
the way C-g is processed is system-dependent.  When I said "this is
not supposed to happen", I assumed you were doing this on GNU/Linux or
another Posix platform.

Indeed, on MS-Windows this is expected behavior: pressing C-g in the
above scenario will set the quit-flag, and the loop will then quit.
To prevent that, you need to use this simple technique:

  (make-thread
   (lambda ()
     (let ((inhibit-quit t))  ;; <<<<<<<<<<<<<<<<<<<<
       (cl-loop
	while t do
	(progn
	  (thread-yield)
	  (sleep-for 30))))))

Btw, my recommendation is to bind inhibit-quit non-nil around the
thread functions in all cases, if you want background thread to never
be interrupted by C-g and the like.