From: Jean-Hugues ROBERT Date: 2002-04-22T17:01:37+09:00 Subject: Re: Threads creating threads creating threads... Hello, "Portable thread stack allocator" At 04:17 22/04/2002 +0900, Tobias Peters wrote: >I once implemented a portable thread library. > > Result was that the process's stack was fragmented into small chunks. > > Thread switching involved setjmp()/longjmp() only, no copying at all. Was > > much faster than native threads... but non-preemptive and not taking any > > advantages of multiprocessor architectures. > >I have no clue how your library works, but it sounds like it be possible >to enhance ruby's implementation with yours? Problem: You want to create portable threads. You discovered the magic about C's setjmp()/longjmp() to switch context. Question: How do you set up the initial context where a thread will start ? CP (Code Pointer) is easy. SP (Stack Pointer) is less easy. Specially on systems where the stack must be in a "special" MMU managed segment (versus anywhere in the heap). Solution: write a stack_alloc( size_t ) that returns a properly initialized jmpbuf: First re-use free block if any available (for the required size, approximately). Else allocate a new block: 0) setjmp() to remember where you are (to return result in step 3) 1) longjmp() to the "deepest" jmpbuf ever allocated so far. 2) Once there, recursively call a "go_deeper_in_stack()" function. Such a function will typically allocate an "auto" array of bytes (beware of compiler optimization about unused var). 3) when deep enough, setjmp() (& remember that jmpbuf as beeing the new "deepest" mark). Previous "deepest" jmpbuf is the result. longjmp() to jmpbuf saved at step 0 to provide result to caller. The main drawback is that you get "fixed size" stacks. i.e. there is no way the MMU can detect that one thread goes deeper in stack and that a new page must be allocated. Should not be an issue on most modern architectures but don't expect to create hundreds of stacks either (specially if minimum stack size is big). Hope this help. I can provide additional details for those interested. Yours, Jean-Hugues --------------------------------------------------------------------------- Web: http://hdl.handle.net/1030.37/1.1 Phone: +33 (0) 4 92 27 74 17