Issue
If I have a thread that is blocked on a socket for incoming data, how is it rescheduled back to the CPU? (in context of Linux). I am assuming the OS monitors the FD on a separate thread, and if there is data available, moves the corresponding thread to the RUNNABLE queue. However, I am not exactly sure of this. Also, how is the FD monitored - poll/select
or epoll
? Would appreciate a detailed explanation of this, thanks!
Solution
Conceptually, this is done using low-level waitable notifiable event objects. Different operating systems have different names for them, but the concept is the same.
Waitable objects are useful as a concept because they allow us to reason not only about sockets, but also files (via asynchronous file i/o apis) and any other situation where a thread is placed in a block-waiting state, and something must happen outside of that thread to unblock it.
Every socket, every file, every lock, mutex, or semaphore, every operating-system object that can cause threads to block-wait has such an event object associated with it. (Or is itself such an event object.) When your thread makes a call to an operating-system object which will need to block-wait, the operating system places the thread in waiting state, and notes that this thread is blocked on the associated event object. The call does not return for now; the scheduler gives the remainder of the time slice to some other thread that may have a use for it.
When an interrupt (or other event) occurs, as a result of which the operating-system object decides that the block-wait is over, the operating system checks to see whether a thread is associated with the event object, and if so, it places that thread in ready-to-run state, which means that the scheduler will soon allow that thread to resume execution, which means that the previously mentioned call will return to the caller.
Thus, there is no polling anywhere. Polling is a terrible thing to do under almost any circumstances.
Answered By - Mike Nakis Answer Checked By - David Goodson (WPSolving Volunteer)