From: Jean-Hugues ROBERT Date: 2002-04-21T05:03:16+09:00 Subject: Re: Threads creating threads creating threads... Hello, At 04:08 21/04/2002 +0900, Matt Armstrong wrote: >Tobias Peters writes: >But when a new thread is created, the stack of the current thread is >included in the new thread. So if a child thread always spawns >another thread the stack size will grow infinitely. Isn't it rather the block that refers to the stack, rather than the thread ? If this is the case, one can imagine a Thread factory, that would create a new thread to execute a Method (not a Proc) and that would allocate Thread objects from a singleton thread that has a small depth stack. Something like: class ThreadFactory def ThreadFactory::start() @@request_queue = Queue.new Thread.new { while true do method, response_queue = request_queue.get() response_queue.put( Thread.new { method.call() }) end } end def ThreadFactory::create( a_method_call ) response_queue = Queue.new @@request_queue.put( [a_method_call, response_queue] thread = response_queue.get response_queue = nil return thread end end At init time do a ThreadFactory::start(). When you want to create a new thread do my_thread = ThreadFactory::create( a_method). Not tested at all, just pseudo code (I never looked at Ruby's queue so far, sorry). >Ruby's thread implementation isn't the best. It is slow since >switching threads involves physically copying the stack memory. Very surprising ?! I once implemented a portable thread library. Using setjmp()/longjmp() too. However I implemented thread stacks in the global process stack, using a rather difficult to follow state automata, recursive calls and setjmp()/longjmp() to control the program flow. 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. Yours, Jean-Hugues --------------------------------------------------------------------------- Web: http://hdl.handle.net/1030.37/1.1 Phone: +33 (0) 4 92 27 74 17