How does computer understand that it can switch to the process that waits for data from the network?

85 Views Asked by At

Imagine that we have a computer that does nothing except waiting data from network and does some calculating on it when it is received.

Right now I think that there is no other way to do this besides periodically checking some processor register that indicates that data is ready and then do computing. In my understanding under the hood network card receives the data, put it to the memory and by itself write to the cpu register that cpu can do computing. After the next periodically check processor will compute stuff. Can you make explanation of what actually is happening in details (on hardware and in os). This question worries me for ages!

Also will be glad to see any materials about it!

1

There are 1 best solutions below

0
On BEST ANSWER

The method described in the question of the processor periodically checking some data register is used and it called polling. Polling is often employed in simpler systems because it's simple to implement, but it has the downside of wasting cpu cycles checking for data that may or may not be there.

In practice though most modern operating systems are going to use a cpu hardware feature called interrupts in conjunction with the OS's scheduler. In the example of getting data from the network, the program will use some blocking read call that will wait for data to be received from the network. Once the read call is made the calling program will stop executing completely and the OS's scheduler will keep the program in the suspended state until data is received.

Often, the way a program signals that it wants to wants to stop executing until something happens (like a packet is received) is with a software construct called a semaphore (or similar mutual exclusion mechanism). However, in the case of networking code the semaphore is not directly accessed by the programmer.

When a packet is received by the network card the network card will store the packet into RAM somewhere. Once this is completed the network card triggers an interrupt to the CPU. The interrupt (generally) causes the CPU to stop executing whatever program may have been currently running and the CPU executes kernel code related to handling network activity. In this case it sends the received packet to the program that was waiting to receive the data.

Finally, the kernel uses the semaphore to signal the packet was received. The kernel then has the scheduler "wake up" the program that was waiting for the data from the network. The program can process the data, and then await the next set of data from the network.

If you want to learn more I'd recommend reading op on interrupts, scheduling and semaphores. These technique though are used for more than just networking. Many other IO devices are accessed in with similar approaches.