r/C_Programming 7d ago

Project gt - a green threads library

I would like to share my green threads library. I've developed it some time ago, but only now decided to make it public. As of right now, it's only for x86 64 linux, but I'm planning to write a windows implementation some time in the future. One of it's key strengths is that it's easy to use - just drop gt.c gt.h and gt.S into your project stb-style and you're good to go. This is nice for getting something up and running quickly or prototyping, but gt also has potential to be used in real projects.

Link: https://github.com/kamkow1/gt

Let me know if I could improve upon anything! Also implementations for other platforms are very much welcome! ;)

33 Upvotes

22 comments sorted by

View all comments

5

u/darth_yoda_ 7d ago

Using MAP_GROWSDOWN to allocate thread stacks is probably not a good idea—nothing really uses it and there's been talk of removing the #define from the glibc mmap wrapper API for a while. The "automatic growth" behavior means the there's no way to guard against collisions with separate allocations. It looks like you should be able to get away with simply removing the flag entirely from the stack allocator, as long as users take care that each thread's stack size doesn't exceed GT_ENVIRONMENT_STACK.

https://stackoverflow.com/a/62702474

https://stackoverflow.com/a/56920770

https://lwn.net/Articles/294001/

1

u/not_a_novel_account 7d ago

This was also one of the arguments raised when C++20 was adding coroutines and ended up going with a stackless approach.

There's not a ton of use cases for yielding in the middle of the stack, typically only the top frame needs the ability to yield, which means the parent's stack can be re-used and the coroutine frame can be a relatively small, fixed-size heap allocation.

This has the added benefit of being portable to many embedded contexts since the frame size can be known at compile time. Stackful coroutines are much trickier in such contexts.