Normally, you would need to use a syscall to retrieve the ID of current thread. This code, however, thinks a syscall would be slow, so it stored the ID on the stack of each thread when they are created so that a thread can get its own ID by just reading the its stack. So the code kinda uses undefined behaviors to save the time for a syscall.
It's up to the compiler. Some optimization may break this mechanism. (as you can see, the code uses 'volatile' to avoid the optimization of some variables)
5
u/ameer-sheriff Sep 17 '21
Can anyone explain what the code is doing?
4
u/FloweyTheFlower420 sadistic Sep 17 '21
This isn’t terrible, syscalls are slow due to context switching
4
u/weebitanon Sep 17 '21
Wow. I struck gold! Thanks OP
9
u/teapot_on_reddit Sep 17 '21 edited Sep 17 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
0
u/[deleted] Sep 17 '21
[deleted] — view deleted comment
0
u/[deleted] Sep 17 '21
[deleted] — view deleted comment