Subject: bug#34821: discard_input_tty does not discard pending input, resulting in garbage inserted into the buffer

From: Eli Zaretskii <[email-masked]>
Date: Sun, 07 Apr 2019 21:24:58 +0300

> From: Platon Pronko <[email-masked]>
> Date: Sun, 7 Apr 2019 20:14:21 +0300
> 
> I guess that something in (terminal-init-xterm) hooks results in some buffer switch event being fired, that triggers the second return from read_char(). But since (terminal-init-xterm) and read_key_sequence() run concurrently, we have a race condition - if the terminal responds quickly enough, second buffer switch does not trigger quick enough and this problem happens.

What do you mean by "run concurrently"?  Emacs is pretty much a single
threaded program, and there's only one Lisp thread running at any
given time, which will execute both calls.

> Maybe trying to rely on terminal being slow with the response is not the best solution? Even if I find a cause of the buffer switch event, we won't have a way to ensure that it always arrives before the response to SDA query (because multithreading).

You may be right, but my reasoning was that without knowing why
there's a second buffer-switch event sometimes, we will be unable to
devise a good solution.  IOW, I think we need to understand the issue
better before we are ready to discuss a solution.