Handmade Hero»Forums»Code
Nuno
18 posts
Day 178: Compiling on Linux
Edited by Nuno on
Kim

Regarding the assembly wouldn't it be simpler to do this?

1
2
3
4
5
6
inline u32 GetThreadID(void)
{
   u32 ThreadID;
   asm("mov %%gs:0x0,%0" : "=r"(ThreadID));
   return ThreadID;
}


Indeed and it seems to work just fine. :D Sometimes I overcomplicate without any reason to.

Does it also work in Linux ?

Thanks a lot :)
Mārtiņš Možeiko
2562 posts / 2 projects
Day 178: Compiling on Linux
Edited by Mārtiņš Možeiko on
Technically pthread_self returns pointer sized value. So it more correct to get it all, and then cast it to whatever you want. It works with u32 only because of values are stored in memory in little-endian.

It won't work on Linux. On Linux TLS is implemented differently. Look the topic Kim linked - https://forums.handmadehero.org/i...p/forum?view=topic&catid=4&id=837
Nuno
18 posts
Day 178: Compiling on Linux
mmozeiko
Technically pthread_self returns pointer sized value. So it more correct to get it all, and then cast it to whatever you want. It works with u32 only because of values are stored in memory in little-endian.

It won't work on Linux. On Linux TLS is implemented differently. Look the topic Kim linked - https://forums.handmadehero.org/i...p/forum?view=topic&catid=4&id=837


So in order to achieve portability of code between Linux and OSX, which is what I think we were trying to achieve here, the best way would be to use pthread_self instead of direct assembly, is that correct ?
Mārtiņš Možeiko
2562 posts / 2 projects
Day 178: Compiling on Linux
If you are OK with including platform specific headers (pthread.h) in game dll layer, then sure, that would work.

Casey was not OK to do that. He didn't want to include windows.h in game dll to be able to use GetCurrentThreadId. And he put code in #ifdef. You can do the same:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
inline u32 GetThreadID(void)
{
#elif HANDMADE_OSX
   u32 ThreadID;
   asm("mov %%gs:0x0,%0" : "=r"(ThreadID));
   return ThreadID;
#elif HANDMADE_LINUX
   ...
#elif HANDMADE_WIN32
   ...
#else
#error How to get current thread id for this OS?
#endif
}
Nuno
18 posts
Day 178: Compiling on Linux
Thank you very much.

I got a little bit carried away with the different options and I forgot about the dependency of pthread.

I think that your proposal is the sane thing to do.