[plt-scheme] Creating a suspended thread

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Mon Apr 13 10:24:00 EDT 2009

At Mon, 13 Apr 2009 16:36:45 +0300, R. Emre Başar wrote:
> I'm tryring to create a thread which is initially suspended.  As far as
> I know, (thread (lambda () ...)) creates a thread and runs it instantly.
> Is it possible to create a thread in suspended state to resume later?
> 
> I know it's possible to create and suspend it afterwards but our
> application is rather time intensive so I don't want it to have even a
> little chance to run.

Matthias asks a good question, but...

 (define (thread/suspended thunk)
   (let* ([s (make-semaphore)]
          [t (thread (lambda ()
                       (semaphore-wait s)
                       (thunk)))])
     (thread-suspend t)
     (semaphore-post s)
     t))

In practice, `thread-suspend' will suspend the new thread before it is
ever swapped in. In the unlikely event that the creating thread is
swapped out before it can suspend the new one, the semaphore prevents
the new thread from making any progress. (The semaphore operations are
all cheap.)



Posted on the users mailing list.