Can a thread be proactive in the middle of a kernel system call?

I am running 2 threads (suppose they are pthreads at the moment). Thread_1 () creates a custom API call that ultimately does some work in the kernel. Thread_2 () is entirely in user space.

My question is: can Thread_2 () start execution using pre-empting Thread_1 (), while the API call is executed, the control is somewhere inside the kernel? If not, then why, and if I want this scenario to happen (for whatever reason), what should I do?

+7
c ++ c multithreading pthreads
source share
3 answers

If you ask if a call to a blocking kernel such as fread() , which requires an IO drive, can be blocked, then yes.

In particular, a blocking call will basically put Thread_1 on hold, waiting for what it expects. If Thread_1 is asleep, then Thread_2 will be scheduled to run (unless something higher priority is expected).

Edit:. If you want to be β€œsure enough” that Thread_1 is making a blocking call, make Thread_2 a lower priority than Thread_1 (so that it does not start at all if Thread_1 is not blocked), and when it starts, it raises the priority to more higher than Thread_1, until a hardware interrupt is delivered, at which point it lowers the priority and calls sched_yield() .

+5
source share

Calls to the kernel are considered either blocking or non-blocking. A blocking call (for example, waiting to read data from a network socket) can, of course, be unloaded without any action required on your part. Other threads will continue to work. Non-blocking kernel calls can be considered very fast and, in practical terms, it does not matter whether you really squeeze them out or not.

As a rule, when writing multi-threaded code, you concentrate on how these threads interact with each other and leave their interaction with the kernel to the kernel for control. It is designed for a very good job.

+8
source share

It depends on the kernel. Classic kernels do not allow prevention (with the exception of special points when he will sleep a thread). But newer kernels have the ability to enable preemption inside the kernel itself.

Linux supports the proactive kernel when it is built using CONFIG_PREEMPT. From the kernel documentation:

This parameter reduces kernel latency, making all kernel code (which is not executed in the critical section) interrupted. This allows you to respond to interactive ones, allowing you to forcefully supplant a low-priority process even if it performs a system call in kernel mode and otherwise will not reach the natural point of preemptive right. This allows applications to run smoothly, even if the system is under load, due to a slightly lower throughput and a small workload while working with kernel code.

Choose this if you are creating a desktop kernel or embedded system with delay requirements in the millisecond range.

+7
source share

All Articles