12

I'm doing some research in C++ green threads, mostly boost::coroutine2 and similar POSIX functions like makecontext()/swapcontext(), and planning to implement a C++ green thread library on top of boost::coroutine2. Both require the user code to allocate a stack for every new function/coroutine.

My target platform is x64/Linux. I want my green thread library to be suitable for general use, so the stacks should expand as required (a reasonable upper limit is fine, e.g. 10MB), it would be great if the stacks could shrink when too much memory is unused (not required). I haven't figured out an appropriate algorithm to allocate stacks.

After some googling, I figured out a few options myself:

  1. use split stack implemented by the compiler (gcc -fsplit-stack), but split stack has performance overhead. Go has already moved away from split stack due to performance reasons.
  2. allocate a large chunk of memory with mmap() hope the kernel is smart enough to leave the physical memory unallocated and allocate only when the stacks are accessed. In this case, we are at the mercy of the kernel.
  3. reserve a large memory space with mmap(PROT_NONE) and setup a SIGSEGV signal handler. In the signal handler, when the SIGSEGV is caused by stack access (the accessed memory is inside the large memory space reserved), allocate needed memory with mmap(PROT_READ | PROT_WRITE). Here is the problem for this approach: mmap() isn't asynchronous safe, cannot be called inside a signal handler. It still can be implemented, very tricky though: create another thread during program startup for memory allocation, and use pipe() + read()/write() to send memory allocation information from the signal handler to the thread.

A few more questions about option 3:

  1. I'm not sure the performance overhead of this approach, how well/bad the kernel/CPU performs when the memory space is extremely fragmented due to thousands of mmap() call ?
  2. Is this approach correct if the unallocated memory is accessed in kernel space ? e.g. when read() is called ?

Are there any other (better) options for stack allocation for green threads ? How are green thread stacks allocated in other implementations, e.g. Go/Java ?

user416983
  • 974
  • 3
  • 18
  • 28
  • 2
    While `mmap` is not async safe according to POSIX, it is actually async safe in Linux and pretty much every reasonable, usable UNIX variant out there. – Chris Dodd Feb 01 '16 at 05:05
  • @ChrisDodd Can I ask why `mmap` can be good for green threads? I'm not an expert but I wanted to know. – CinchBlue Feb 01 '16 at 05:07
  • @ChrisDodd I haven't find any man page/link on this, could you mind please give me a link ? – user416983 Feb 01 '16 at 05:38
  • FWIW, I do not know if Linux shared memory fits your needs. But I used that for a high-performance backend to a google maps application a few years ago, and the performance was very good. – Erik Alapää Feb 01 '16 at 08:37
  • @ErikAlapää Green threads all run on the same kernel thread, so they share the same address space. https://en.wikipedia.org/wiki/Green_threads – user416983 Feb 01 '16 at 09:35
  • @user416983 Yeah right, then you obviously will not need shared mem. – Erik Alapää Feb 01 '16 at 10:17
  • why not use stackless coroutines? – ALGOholic Feb 15 '16 at 06:38
  • @ALGOholic Stackless coroutines can only support very limited suspend/resume operations, but my goal is to develop a library suitable for general use, I don't want such limitations on my library. – user416983 Feb 15 '16 at 07:09
  • I believe in most cases where you'd want to use coroutines/green threads (i.e. asynchronous I/O) the stackless suspend/resume is sufficient. What's the use case for your library? – ALGOholic Feb 15 '16 at 07:55
  • @ALGOholic Actually ATM it's exactly asynchronous I/O that I want to get rid of, mainly because asynchronous code tends to be more difficult to understand (I know it's more efficient). As I said in the main question, I'm doing some _research_, so use cases aren't that important. – user416983 Feb 15 '16 at 08:03
  • hmm but ASIO implemented via coroutines (i.e. boost::asio) is kinda _the_ way to go imho. anyway - why not base it on boost::asio, it has already a spawn() method which allocates the stack. also you could use one of the C libraries - libtask / libconcurrency - both allocate stack for you. – ALGOholic Feb 15 '16 at 08:10
  • How well do C++ exceptions propagate under libtask/libconcurrency ? I did a brief googling, haven't even find out whether it's supported. – user416983 Feb 15 '16 at 08:25
  • I don't think it's explicitly supported but as long as the compiler doesn't do some weird OS-specific stuff, all data necessary for correct exception handling (stack unwinding) should be on the stack anyway. One special case might be Windows and SEH as I've heard exception handling is partly implemented using that mechanism, so potentially as part of context switch you need to switch SEH handlers chain as well? – ALGOholic Feb 15 '16 at 09:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/103472/discussion-between-user416983-and-algoholic). – user416983 Feb 15 '16 at 10:58
  • If a stack area can contain a pointer to something inside the stack area, how will you relocate the stack area if it grows? If you aren't relocating it, then you'll have to allocate the max needed when you start. – Ira Baxter Feb 15 '16 at 14:45

2 Answers2

3

The way that glibc allocates stacks for normal C programs is to mmap a region with the following mmap flag designed just for this purpose:

   MAP_GROWSDOWN
          Used for stacks.  Indicates to the kernel virtual memory  system
          that the mapping should extend downward in memory.

For compatibility, you should probably use MAP_STACK too. Then you don't have to write the SIGSEGV handler yourself, and the stack grows automatically. The bounds can be set as described here What does "ulimit -s unlimited" do?

If you want a bounded stack size, which is normally what people do for signal handlers if they want to call sigaltstack(2), just issue an ordinary mmap call.

The Linux kernel always maps physical pages that back virtual pages, catching the page fault when a page is first accessed (perhaps not in real-time kernels but certainly in all other configurations). You can use the /proc/<pid>/pagemap interface (or this tool I wrote https://github.com/dwks/pagemap) to verify this if you are interested.

Community
  • 1
  • 1
dwks
  • 602
  • 5
  • 10
  • I've heard that `MAP_GROWSDOWN` can cause some sorts of problems. Is this still true today? – bb94 Jun 26 '19 at 23:29
0

Why mmap? When you allocate with new (or malloc) the memory is untouched and definitely not mapped.

const int STACK_SIZE = 10 * 1024*1024;
char*p = new char[STACK_SIZE*numThreads];

p now has enough memory for the threads you want. When you need the memory, start accessing p + STACK_SIZE * i

Dov
  • 8,000
  • 8
  • 46
  • 75
  • 3
    That's definitely not guaranteed to be unmapped, or initialized to any value in particular. Using the GNU libc malloc, that large of an allocation will ultimately call mmap() anyway. – Matt Feb 17 '16 at 23:12