s c h e m a t i c s : c o o k b o o k

/ Cookbook.ThreadSuspendingCurrentThread

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Suspending the Current Thread

Problem

You wish to indefinitely suspend the current thread

Solution

There are two good solutions:

(sync (make-semaphore))
(thread-wait (current-thread))

Discussion

Why would you ever want to suspend the current thread? Say you are writing a server with the following architecture: the main thread does some setup, creates some worker threads to handle requests, and then has nothing to do. The main thread cannot exit, because MzScheme will exit if it does. Hence it is necessary to suspend the current thread.

If there was only one worker thread, you could wait until it exited:

(sync/enable-break worker-thread)

Notice the call to sync/enable-break, not sync. Normally breaks are enabled, so this call is equivalent to just sync, but in case they aren't it is good practice to enable them, as it allows the main thread to be interrupted by Control-C.

Two idioms you shouldn't use are:

(let loop () (loop))  ;; busy wait
(thread-suspend (current-thread))

The former is an infinite loop, which needlessly consumes CPU resources. The later will stop the main thread handling break signals. If all the worker threads exit without resuming the main thread MzScheme will complain with "unbreakable deadlock" and immediately exit.


Comments about this recipe

NB: Based on advice supplied by MatthewFlatt? on the PltScheme mailing list 13/06/2006.

Hmm. Why not wait on all the threads? It seems your way, the program will never exit, unless one of the child threads actually calls "exit", which seems dangerous.

Contributors

-- NoelWelsh - 13 Jun 2006

CookbookForm
TopicType: Recipe
ParentTopic: ThreadRecipes
TopicOrder: 999

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest