[comp.os.os2.programmer] Recovering a Dead Thread's Stack

"Ken Borgendale" <kwb@betasvm2.vnet.ibm.com> (05/20/91)

The stack for a thread belongs to the parent thread, which passes it
in _beginthread (or DosCreateThread).  The parent thread can wait
or check for the death of the child and then do what it likes with
the storage associated with the child thread's stack.

feustel@netcom.COM (David Feustel) (05/21/91)

The exiting thread can enter a critical section, set a flag saying the
stack is free, and then do a programexit call. This works for
single process code only.
-- 
David Feustel, 1930 Curdes Ave, Fort Wayne, IN 46805, (219) 482-9631
EMAIL: feustel@netcom.com  or feustel@cvax.ipfw.indiana.edu

kenr@arcade.uucp (Ken Reneris) (05/25/91)

| The stack for a thread belongs to the parent thread, which passes it
| in _beginthread (or DosCreateThread).  The parent thread can wait
| or check for the death of the child and then do what it likes with
| the storage associated with the child thread's stack.

The ways to do this seem to be:

  o The main thread can poll for when the sub-thread has called
    DosExit.  (You can tell if a TID is bad by calling various
    api - like, DosGetPrty)

  o The sub-thread can queue up it's strucutre before calling
    DosExit to say 'hey, I'm dead'.

      ...
      DosEnterCritSec
      add myself to queue (or even free the memory)
      (kick semaphore to notify main thread)
      DosExit

      // Note you don't call DosExitCritSec. It's automatically
      // exited when the thread terminates.  This allows you to
      // do your cleanup and without having one of your other
      // threads pick it up half way.
      //
      // Note2: the queue has to be per-process, since that's all
      // the EnterCritSec provides


  o If you simply want to set a flag, (Or are using a word LL
    and you queue up with xchg) you can do the same thing without
    calling EnterCritSec:

	mov ss:sp to 4 byte dumby stack area
	set flag saying our stack has been freed and it can be re-used.
	call DosExit


    Hmm.. since I've never read that DosExit doesn't require any R3
    stack I'm not sure if this is legal.  The basic idea is that
    more then one thread can use the '4 byte stack' to call DosExit.
    Since the threads never return and are passing in the same parameters,
    it's not a problem that they are using the same memory for their stacks.


Beyond this, my code normally doesn't free threads and stacks right
away. (Allocating one is cheap, but not free). A thread waits until it's not
needed for some amount of time (10 seconds), then it frees itself.

	- Ken

--
{uunet,uw-beaver}!microsoft!arcade!kenr

feustel@netcom.COM (David Feustel) (05/26/91)

DosExit plays with the Stack before a final exit is achieved. If you
mess with the stack DosExit may not terminate properly.
-- 
David Feustel, 1930 Curdes Ave, Fort Wayne, IN 46805, (219) 482-9631
EMAIL: feustel@netcom.com  or feustel@cvax.ipfw.indiana.edu