Deadlock detection fails when unrelated threads are waiting on I/O, in non-threaded RTS
In the non-threaded RTS, the deadlock detection is only invoked if both of these conditions hold:
1. the run queue is empty
2. there is no pending I/O or timeouts
The second condition is bogus and leads to the symptom that deadlock detection fails to detect blocked threads if there are any threads waiting on I/O or timers.
In the threaded RTS condition 2 is vacuously true and so there is no problem.
Here is a test case
```
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
main :: IO ()
main = do
-- Set up two threads that are blocked on each other
aDone <- newTVarIO False
bDone <- newTVarIO False
let blockingThread theirDone ourDone =
atomically $ do
done <- readTVar theirDone
guard done
writeTVar ourDone True
_ <- forkIO (blockingThread bDone aDone)
_ <- forkIO (blockingThread aDone bDone)
-- Set up another thread that is blocked on I/O
_ <- forkIO $ threadWaitRead 0
-- Wait on the blocked threads terminating. We would hope that the threads
-- that are deadlocked are detected as such and get an exception raised. The
-- fact that another thread is blocked on I/O should not matter to this.
-- Historically however this did affect things in the non-threaded RTS which
-- would only do deadlock detection if there were no runnable threads *and*
-- no pending I/O.
atomically $ do
status <- mapM readTVar [aDone, bDone]
guard (or status)
```
Related: #20947 which cleaned some of this stuff up.
The solution is almost but not quite as simple as deleting the condition 2. That is a necessary but not sufficient change. The other change needed is to refactor where the scheduler blocks to wait on on I/O (in the non-threaded RTS). Currently it will block in `scheduleFindWork` _before_ the call to `scheduleDetectDeadlock`. This means the scheduler blocks on I/O before it has a chance to look for deadlocks.
This should be changed so that we only _poll_ for I/O in `scheduleFindWork` and we add an action to block on I/O (if the run queue is empty and there's I/O outstanding) _after_ the the call to `scheduleDetectDeadlock`.
I have a local patch for this bug. It fixes this test case. I'll file an MR and include this test case as a regression test and get CI to check for me that this change doesn't break anything else.
issue