I'm trying to figure out which codes of c++ can cause the mode switch (user mode to kernel mode) on Linux. And I've known two things:
- A system call cause the mode switch: Is mode switch occur switching from user thread to kernel thread?
- The command
strace
can list all of the system calls.
Now I write such a code as below to do a test:
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
int i = 0;
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
i++;
}
return 0;
}
I compile it with the command g++ -std=c++11 test.cpp -lpthread
and then I run strace -ttT ./a.out
to list its system calls. Here is the output:
22:08:52.424382 prlimit64(0, RLIMIT_STACK, NULL, {rlim_cur=8192*1024, rlim_max=RLIM64_INFINITY}) = 0 <0.000009>
22:08:52.424611 brk(NULL) = 0x55ca3968b000 <0.000009>
22:08:52.424725 brk(0x55ca396ac000) = 0x55ca396ac000 <0.000011>
22:08:52.424887 futex(0x7f0aad83909c, FUTEX_WAKE_PRIVATE, 2147483647) = 0 <0.000010>
22:08:52.425070 futex(0x7f0aad8390a8, FUTEX_WAKE_PRIVATE, 2147483647) = 0 <0.000010>
22:08:52.425246 nanosleep({tv_sec=1, tv_nsec=0}, 0x7ffcae110cb0) = 0 <1.000142>
22:08:53.425553 nanosleep({tv_sec=1, tv_nsec=0}, 0x7ffcae110cb0) = 0 <1.000253>
22:08:54.425924 nanosleep({tv_sec=1, tv_nsec=0}, 0x7ffcae110cb0) = 0 <1.000138>
22:08:55.426177 nanosleep({tv_sec=1, tv_nsec=0}, 0x7ffcae110cb0) = 0 <1.000145>
22:08:56.426455 nanosleep({tv_sec=1, tv_nsec=0}, 0x7ffcae110cb0) = 0 <1.000141>
22:08:57.426710 nanosleep({tv_sec=1, tv_nsec=0}, 0x7ffcae110cb0) = 0 <1.000146>
22:08:58.426967 nanosleep({tv_sec=1, tv_nsec=0}, 0x7ffcae110cb0) = 0 <1.000146>
Now I have some questions:
- Why is there
futex
? As far as I know,futex
is the lower mechanism to implement to thread mutex in c++11, but I haven't used any mutex here so why is therefutex
? - We can see that there are infinite
nanosleep
, so does this mean that the c++11 codestd::this_thread::sleep_for(std::chrono::milliseconds(1000));
will cause the mode switch from user mode to kernel mode? - Is there a better way to check which c++ codes/functions will cause the mode switch or I have to use the command
strace
?
Aucun commentaire:
Enregistrer un commentaire