I'm wondering does sleep()
/nanosleep()
cause a process to give up the remainder of its time slice immediately? And can other threads or processes utilize the rest of the time slice directly?
I wrote a program called nanosleep()
to sleep n nanoseconds repeatedly. Can I use this program to prove the system calls indeed cause the process to give up its rest of time slice immediately if the times of nanosleep() called is as many as the count of context switch occurred?
#include <stdio.h>#include <time.h>#include <sched.h>#include <sys/types.h>#include <unistd.h>int main() { struct timespec tim, tim2; tim.tv_sec = t.tv_sec; tim.tv_nsec = 1000000; // n nanoseconds int ret; while (1) { ret = nanosleep(&tim, &tim2); if (ret < 0) { perror("nano sleep"); } }}
n is much less than a time slice.
e.g. when the n = 1000000(= 1ms = 1/1000s), the cs
column value from vmstat 1
command is 1400~1600,and when the n = 2000000(= 2ms), the cs column value is 800~900