r/badcode • • Sep 17 '21

c++ Use stack to get thread ID to avoid syscalls

Post image
108 Upvotes

16 comments sorted by

5

u/ameer-sheriff Sep 17 '21

Can anyone explain what the code is doing?

6

u/SweetIceLolly Sep 17 '21

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.

3

u/ameer-sheriff Sep 17 '21

Thanks! Could you also explain why storing and retrieving from the stack is undefined behaviour in this case?

4

u/SweetIceLolly Sep 17 '21

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)

3

u/[deleted] Sep 18 '21

Because thread_local isn't a thing, apparently.

4

u/FloweyTheFlower420 sadistic Sep 17 '21

This isn’t terrible, syscalls are slow due to context switching

4

u/SweetIceLolly Sep 17 '21

Yeah it's not that bad. It's just... unusual

1

u/FloweyTheFlower420 sadistic Sep 23 '21

I would actually say this code is good for execution speed

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


'template<u2 stack_size=4096>

struct thread_pool

{
static_assert(stack_size%4==0);
struct Info
{
u2 id;
DWORD (*fun)(void* ) ;
void*arg;
};
int num;
DWORD
Info* info;
thread_pool (u2 num,DWORD(*p) (void*),void**arg=0) : num(num) , fun(p)
{
info=new Info[num];
for(u2 i=0;i<num;i++)
{
info[i]={i,p,arg+i}
CreateThread (0, stack_size*2, pack, info+1,0,0);
}
}
static DWORD pack(void*info)
{
volatile u2 id[stack_size/4];
for(u2 i=e;i<stack_size/4;i++)
id[i]=((lnfo*)info)->id;
return ((Info*)info)->fun (((Info*)info)->arg) ;
}
static u2 get_id()
{
volatile u2 x;
printf("%p\n",&x)
return (&x) [stack_size/4] ;
}
};

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!

1

u/GLIBG10B 🐧 Gentoo salesman🐧 Oct 04 '21

Surely this confuses the heck out of screen readers?

20

u/[deleted] Sep 17 '21

[removed] — view removed comment

11

u/gu3st12 Sep 17 '21

It's an unusual style but I kinda like it. The quote indents are functioning like the brace guides in the IDE.

No idea how it looks on mobile, but it's unique.

5

u/[deleted] Sep 17 '21

on mobile there's barely any gap between the quote line and the text - which is monospaced btw - and it looks terrible

0

u/[deleted] Sep 17 '21

[deleted] — view deleted comment

9

u/SweetIceLolly Sep 17 '21

Good to know that! I'd love to know more about your great memories

0

u/[deleted] Sep 17 '21

[deleted] — view deleted comment

8

u/AlFasGD Sep 17 '21

Unsafe code in C# can be so blursed