File: gambit-c.info, Node: Threads, Next: Dynamic environment, Prev: Records, Up: Top
13 Threads
**********
Gambit supports the execution of multiple Scheme threads. These
threads are managed entirely by Gambit's runtime and are not related to
the host operating system's threads. Gambit's runtime does not
currently take advantage of multiprocessors (i.e. at most one thread is
running).
* Menu:
* Introduction:: Introduction
* Thread objects:: Thread objects
* Mutex objects:: Mutex objects
* Condition variable objects:: Condition variable objects
* Fairness:: Fairness
* Memory coherency:: Memory coherency
* Timeouts:: Timeouts
* Primordial thread:: Primordial thread
* Procedures:: Procedures
File: gambit-c.info, Node: Introduction, Next: Thread objects, Prev: Threads, Up: Threads
13.1 Introduction
=================
Multithreading is a paradigm that is well suited for building complex
systems such as: servers, GUIs, and high-level operating systems.
Gambit's thread system offers mechanisms for creating threads of
execution and for synchronizing them. The thread system also supports
features which are useful in a real-time context, such as priorities,
priority inheritance and timeouts.
The thread system provides the following data types:
* Thread (a virtual processor which shares object space with all
other threads)
* Mutex (a mutual exclusion device, also known as a lock and binary
semaphore)
* Condition variable (a set of blocked threads)
File: gambit-c.info, Node: Thread objects, Next: Mutex objects, Prev: Introduction, Up: Threads
13.2 Thread objects
===================
A "running thread" is a thread that is currently executing. A
"runnable thread" is a thread that is ready to execute or running. A
thread is "blocked" if it is waiting for a mutex to become unlocked, an
I/O operation to become possible, the end of a "sleep" period, etc. A
"new thread" is a thread that has been allocated but has not yet been
initialized. An "initialized thread" is a thread that can be made
runnable. A new thread becomes runnable when it is started by calling
`thread-start!'. A "terminated thread" is a thread that can no longer
become runnable (but "deadlocked threads" are not considered
terminated). The only valid transitions between the thread states are
from new to initialized, from initialized to runnable, between runnable
and blocked, and from any state except new to terminated as indicated in
the following diagram:
unblock
start <-------
NEW -------> INITIALIZED -------> RUNNABLE -------> BLOCKED
\ | block /
\ v /
+-----> TERMINATED <----+
Each thread has a "base priority", which is a real number (where a
higher numerical value means a higher priority), a "priority boost",
which is a nonnegative real number representing the priority increase
applied to a thread when it blocks, and a "quantum", which is a
nonnegative real number representing a duration in seconds.
Each thread has a "specific field" which can be used in an
application specific way to associate data with the thread (some thread
systems call this "thread local storage").
Each thread has a "mailbox" which is used for inter-thread
communication.
File: gambit-c.info, Node: Mutex objects, Next: Condition variable objects, Prev: Thread objects, Up: Threads
13.3 Mutex objects
==================
A mutex can be in one of four states: "locked" (either "owned" or "not
owned") and "unlocked" (either "abandoned" or "not abandoned").
An attempt to lock a mutex only succeeds if the mutex is in an
unlocked state, otherwise the current thread will wait. A mutex in the
locked/owned state has an associated "owner thread", which by
convention is the thread that is responsible for unlocking the mutex
(this case is typical of critical sections implemented as "lock mutex,
perform operation, unlock mutex"). A mutex in the locked/not-owned
state is not linked to a particular thread.
A mutex becomes locked when a thread locks it using the
`mutex-lock!' primitive. A mutex becomes unlocked/abandoned when the
owner of a locked/owned mutex terminates. A mutex becomes
unlocked/not-abandoned when a thread unlocks it using the
`mutex-unlock!' primitive.
The mutex primitives do not implement "recursive mutex semantics".
An attempt to lock a mutex that is locked implies that the current
thread waits even if the mutex is owned by the current thread (this can
lead to a deadlock if no other thread unlocks the mutex).
Each mutex has a "specific field" which can be used in an
application specific way to associate data with the mutex.
File: gambit-c.info, Node: Condition variable objects, Next: Fairness, Prev: Mutex objects, Up: Threads
13.4 Condition variable objects
===============================
A condition variable represents a set of blocked threads. These blocked
threads are waiting for a certain condition to become true. When a
thread modifies some program state that might make the condition true,
the thread unblocks some number of threads (one or all depending on the
primitive used) so they can check if the condition is now true. This
allows complex forms of interthread synchronization to be expressed more
conveniently than with mutexes alone.
Each condition variable has a "specific field" which can be used in
an application specific way to associate data with the condition
variable.
File: gambit-c.info, Node: Fairness, Next: Memory coherency, Prev: Condition variable objects, Up: Threads
13.5 Fairness
=============
In various situations the scheduler must select one thread from a set of
threads (e.g. which thread to run when a running thread blocks or
expires its quantum, which thread to unblock when a mutex becomes
unlocked or a condition variable is signaled). The constraints on the
selection process determine the scheduler's "fairness". The selection
depends on the order in which threads become runnable or blocked and on
the "priority" attached to the threads.
The definition of fairness requires the notion of time ordering,
i.e. "event A occured before event B". For the purpose of establishing
time ordering, the scheduler uses a clock with a discrete, usually
variable, resolution (a "tick"). Events occuring in a given tick can
be considered to be simultaneous (i.e. if event A occured before event
B in real time, then the scheduler will claim that event A occured
before event B unless both events fall within the same tick, in which
case the scheduler arbitrarily chooses a time ordering).
Each thread T has three priorities which affect fairness; the "base
priority", the "boosted priority", and the "effective priority".
* The "base priority" is the value contained in T's "base priority"
field (which is set with the `thread-base-priority-set!'
primitive).
* T's "boosted flag" field contains a boolean that affects T's
"boosted priority". When the boosted flag field is false, the
boosted priority is equal to the base priority, otherwise the
boosted priority is equal to the base priority plus the value
contained in T's "priority boost" field (which is set with the
`thread-priority-boost-set!' primitive). The boosted flag field is
set to false when a thread is created, when its quantum expires,
and when "thread-yield!" is called. The boosted flag field is set
to true when a thread blocks. By carefully choosing the base
priority and priority boost, relatively to the other threads, it
is possible to set up an interactive thread so that it has good
I/O response time without being a CPU hog when it performs long
computations.
* The "effective priority" is equal to the maximum of T's boosted
priority and the effective priority of all the threads that are
blocked on a mutex owned by T. This "priority inheritance" avoids
priority inversion problems that would prevent a high priority
thread blocked at the entry of a critical section to progress
because a low priority thread inside the critical section is
preempted for an arbitrary long time by a medium priority thread.
Let P(T) be the effective priority of thread T and let R(T) be the
most recent time when one of the following events occurred for thread
T, thus making it runnable: T was started by calling `thread-start!', T
called `thread-yield!', T expired its quantum, or T became unblocked.
Let the relation NL(T1,T2), "T1 no later than T2", be true if
P(T1)R(T2), and false otherwise. The
scheduler will schedule the execution of threads in such a way that
whenever there is at least one runnable thread, 1) within a finite time
at least one thread will be running, and 2) there is never a pair of
runnable threads T1 and T2 for which NL(T1,T2) is true and T1 is not
running and T2 is running.
A thread T expires its quantum when an amount of time equal to T's
quantum has elapsed since T entered the running state and T did not
block, terminate or call `thread-yield!'. At that point T exits the
running state to allow other threads to run. A thread's quantum is
thus an indication of the rate of progress of the thread relative to
the other threads of the same priority. Moreover, the resolution of
the timer measuring the running time may cause a certain deviation from
the quantum, so a thread's quantum should only be viewed as an
approximation of the time it can run before yielding to another thread.
Threads blocked on a given mutex or condition variable will unblock
in an order which is consistent with decreasing priority and increasing
blocking time (i.e. the highest priority thread unblocks first, and
among equal priority threads the one that blocked first unblocks first).
File: gambit-c.info, Node: Memory coherency, Next: Timeouts, Prev: Fairness, Up: Threads
13.6 Memory coherency
=====================
Read and write operations on the store (such as reading and writing a
variable, an element of a vector or a string) are not atomic. It is an
error for a thread to write a location in the store while some other
thread reads or writes that same location. It is the responsibility of
the application to avoid write/read and write/write races through
appropriate uses of the synchronization primitives.
Concurrent reads and writes to ports are allowed. It is the
responsibility of the implementation to serialize accesses to a given
port using the appropriate synchronization primitives.
File: gambit-c.info, Node: Timeouts, Next: Primordial thread, Prev: Memory coherency, Up: Threads
13.7 Timeouts
=============
All synchronization primitives which take a timeout parameter accept
three types of values as a timeout, with the following meaning:
* a time object represents an absolute point in time
* an exact or inexact real number represents a relative time in
seconds from the moment the primitive was called
* `#f' means that there is no timeout
When a timeout denotes the current time or a time in the past, the
synchronization primitive claims that the timeout has been reached only
after the other synchronization conditions have been checked. Moreover
the thread remains running (it does not enter the blocked state). For
example, `(mutex-lock! m 0)' will lock mutex `m' and return `#t' if `m'
is currently unlocked, otherwise `#f' is returned because the timeout
is reached.
File: gambit-c.info, Node: Primordial thread, Next: Procedures, Prev: Timeouts, Up: Threads
13.8 Primordial thread
======================
The execution of a program is initially under the control of a single
thread known as the "primordial thread". The primordial thread has an
unspecified base priority, priority boost, boosted flag, quantum, name,
specific field, dynamic environment, `dynamic-wind' stack, and
exception-handler. All threads are terminated when the primordial
thread terminates (normally or not).
File: gambit-c.info, Node: Procedures, Prev: Primordial thread, Up: Threads
13.9 Procedures
===============
-- procedure: current-thread
This procedure returns the current thread. For example:
> (current-thread)
#
> (eq? (current-thread) (current-thread))
#t
-- procedure: thread? OBJ
This procedure returns `#t' when OBJ is a thread object and `#f'
otherwise.
For example:
> (thread? (current-thread))
#t
> (thread? 'foo)
#f
-- procedure: make-thread THUNK [NAME [THREAD-GROUP]]
This procedure creates and returns an initialized thread. This
thread is not automatically made runnable (the procedure
`thread-start!' must be used for this). A thread has the
following fields: base priority, priority boost, boosted flag,
quantum, name, specific, end-result, end-exception, and a list of
locked/owned mutexes it owns. The thread's execution consists of
a call to THUNK with the "initial continuation". This
continuation causes the (then) current thread to store the result
in its end-result field, abandon all mutexes it owns, and finally
terminate. The `dynamic-wind' stack of the initial continuation
is empty. The optional NAME is an arbitrary Scheme object which
identifies the thread (useful for debugging); it defaults to an
unspecified value. The specific field is set to an unspecified
value. The optional THREAD-GROUP indicates which thread group
this thread belongs to; it defaults to the thread group of the
current thread. The base priority, priority boost, and quantum of
the thread are set to the same value as the current thread and the
boosted flag is set to false. The thread's mailbox is initially
empty. The thread inherits the dynamic environment from the
current thread. Moreover, in this dynamic environment the
exception-handler is bound to the "initial exception-handler"
which is a unary procedure which causes the (then) current thread
to store in its end-exception field an uncaught-exception object
whose "reason" is the argument of the handler, abandon all mutexes
it owns, and finally terminate.
For example:
> (make-thread (lambda () (write 'hello)))
#
> (make-thread (lambda () (write 'world)) 'a-name)
#
-- procedure: thread-name THREAD
This procedure returns the name of the THREAD. For example:
> (thread-name (make-thread (lambda () #f) 'foo))
foo
-- procedure: thread-specific THREAD
-- procedure: thread-specific-set! THREAD OBJ
The `thread-specific' procedure returns the content of the
THREAD's specific field.
The `thread-specific-set!' procedure stores OBJ into the THREAD's
specific field and returns an unspecified value.
For example:
> (thread-specific-set! (current-thread) "hello")
> (thread-specific (current-thread))
"hello"
-- procedure: thread-base-priority THREAD
-- procedure: thread-base-priority-set! THREAD PRIORITY
The procedure `thread-base-priority' returns a real number which
corresponds to the base priority of the THREAD.
The procedure `thread-base-priority-set!' changes the base
priority of the THREAD to PRIORITY and returns an unspecified
value. The PRIORITY must be a real number.
For example:
> (thread-base-priority-set! (current-thread) 12.3)
> (thread-base-priority (current-thread))
12.3
-- procedure: thread-priority-boost THREAD
-- procedure: thread-priority-boost-set! THREAD PRIORITY-BOOST
The procedure `thread-priority-boost' returns a real number which
corresponds to the priority boost of the THREAD.
The procedure `thread-priority-boost-set!' changes the priority
boost of the THREAD to PRIORITY-BOOST and returns an unspecified
value. The PRIORITY-BOOST must be a nonnegative real.
For example:
> (thread-priority-boost-set! (current-thread) 2.5)
> (thread-priority-boost (current-thread))
2.5
-- procedure: thread-quantum THREAD
-- procedure: thread-quantum-set! THREAD QUANTUM
The procedure `thread-quantum' returns a real number which
corresponds to the quantum of the THREAD.
The procedure `thread-quantum-set!' changes the quantum of the
THREAD to QUANTUM and returns an unspecified value. The QUANTUM
must be a nonnegative real. A value of zero selects the smallest
quantum supported by the implementation.
For example:
> (thread-quantum-set! (current-thread) 1.5)
> (thread-quantum (current-thread))
1.5
> (thread-quantum-set! (current-thread) 0)
> (thread-quantum (current-thread))
0.
-- procedure: thread-start! THREAD
This procedure makes THREAD runnable and returns the THREAD. The
THREAD must be an initialized thread.
For example:
> (let ((t (thread-start! (make-thread (lambda () (write 'a))))))
(write 'b)
(thread-join! t))
ab> or ba>
NOTE: It is useful to separate thread creation and thread
activation to avoid the race condition that would occur if the
created thread tries to examine a table in which the current
thread stores the created thread. See the last example of the
`thread-terminate!' procedure which contains mutually recursive
threads.
-- procedure: thread-yield!
This procedure causes the current thread to exit the running state
as if its quantum had expired and returns an unspecified value.
For example:
; a busy loop that avoids being too wasteful of the CPU
(let loop ()
(if (mutex-lock! m 0) ; try to lock m but don't block
(begin
(display "locked mutex m")
(mutex-unlock! m))
(begin
(do-something-else)
(thread-yield!) ; relinquish rest of quantum
(loop))))
-- procedure: thread-sleep! TIMEOUT
This procedure causes the current thread to wait until the timeout
is reached and returns an unspecified value. This blocks the
thread only if TIMEOUT represents a point in the future. It is an
error for TIMEOUT to be `#f'.
For example:
; a clock with a gradual drift:
(let loop ((x 1))
(thread-sleep! 1)
(write x)
(loop (+ x 1)))
; a clock with no drift:
(let ((start (time->seconds (current-time)))
(let loop ((x 1))
(thread-sleep! (seconds->time (+ x start)))
(write x)
(loop (+ x 1))))
-- procedure: thread-terminate! THREAD
This procedure causes an abnormal termination of the THREAD. If
the THREAD is not already terminated, all mutexes owned by the
THREAD become unlocked/abandoned and a terminated-thread-exception
object is stored in the THREAD's end-exception field. If THREAD
is the current thread, `thread-terminate!' does not return.
Otherwise `thread-terminate!' returns an unspecified value; the
termination of the THREAD will occur at some point between the
calling of `thread-terminate!' and a finite time in the future
(an explicit thread synchronization is needed to detect
termination, see `thread-join!').
For example:
(define (amb thunk1 thunk2)
(let ((result #f)
(result-mutex (make-mutex))
(done-mutex (make-mutex)))
(letrec ((child1
(make-thread
(lambda ()
(let ((x (thunk1)))
(mutex-lock! result-mutex #f #f)
(set! result x)
(thread-terminate! child2)
(mutex-unlock! done-mutex)))))
(child2
(make-thread
(lambda ()
(let ((x (thunk2)))
(mutex-lock! result-mutex #f #f)
(set! result x)
(thread-terminate! child1)
(mutex-unlock! done-mutex))))))
(mutex-lock! done-mutex #f #f)
(thread-start! child1)
(thread-start! child2)
(mutex-lock! done-mutex #f #f)
result)))
NOTE: This operation must be used carefully because it terminates a
thread abruptly and it is impossible for that thread to perform any
kind of cleanup. This may be a problem if the thread is in the
middle of a critical section where some structure has been put in
an inconsistent state. However, another thread attempting to
enter this critical section will raise an
abandoned-mutex-exception object because the mutex is
unlocked/abandoned. This helps avoid observing an inconsistent
state. Clean termination can be obtained by polling, as shown in
the example below.
For example:
(define (spawn thunk)
(let ((t (make-thread thunk)))
(thread-specific-set! t #t)
(thread-start! t)
t))
(define (stop! thread)
(thread-specific-set! thread #f)
(thread-join! thread))
(define (keep-going?)
(thread-specific (current-thread)))
(define count!
(let ((m (make-mutex))
(i 0))
(lambda ()
(mutex-lock! m)
(let ((x (+ i 1)))
(set! i x)
(mutex-unlock! m)
x))))
(define (increment-forever!)
(let loop () (count!) (if (keep-going?) (loop))))
(let ((t1 (spawn increment-forever!))
(t2 (spawn increment-forever!)))
(thread-sleep! 1)
(stop! t1)
(stop! t2)
(count!)) ==> 377290
-- procedure: thread-join! thread [TIMEOUT [TIMEOUT-VAL]]
This procedure causes the current thread to wait until the THREAD
terminates (normally or not) or until the timeout is reached if
TIMEOUT is supplied. If the timeout is reached, THREAD-JOIN!
returns TIMEOUT-VAL if it is supplied, otherwise a
join-timeout-exception object is raised. If the THREAD terminated
normally, the content of the end-result field is returned,
otherwise the content of the end-exception field is raised.
For example:
(let ((t (thread-start! (make-thread (lambda () (expt 2 100))))))
(do-something-else)
(thread-join! t)) ==> 1267650600228229401496703205376
(let ((t (thread-start! (make-thread (lambda () (raise 123))))))
(do-something-else)
(with-exception-handler
(lambda (exc)
(if (uncaught-exception? exc)
(* 10 (uncaught-exception-reason exc))
99999))
(lambda ()
(+ 1 (thread-join! t))))) ==> 1231
(define thread-alive?
(let ((unique (list 'unique)))
(lambda (thread)
; Note: this procedure raises an exception if
; the thread terminated abnormally.
(eq? (thread-join! thread 0 unique) unique))))
(define (wait-for-termination! thread)
(let ((eh (current-exception-handler)))
(with-exception-handler
(lambda (exc)
(if (not (or (terminated-thread-exception? exc)
(uncaught-exception? exc)))
(eh exc))) ; unexpected exceptions are handled by eh
(lambda ()
; The following call to thread-join! will wait until the
; thread terminates. If the thread terminated normally
; thread-join! will return normally. If the thread
; terminated abnormally then one of these two exception
; objects is raised by thread-join!:
; - terminated-thread-exception object
; - uncaught-exception object
(thread-join! thread)
#f)))) ; ignore result of thread-join!
-- procedure: thread-send THREAD MSG
Each thread has a mailbox which stores messages delivered to the
thread in the order delivered.
The procedure `thread-send' adds the message MSG at the end of the
mailbox of thread THREAD and returns an unspecified value.
For example:
> (thread-send (current-thread) 111)
> (thread-send (current-thread) 222)
> (thread-receive)
111
> (thread-receive)
222
-- procedure: thread-receive [TIMEOUT [DEFAULT]]
-- procedure: thread-mailbox-next [TIMEOUT [DEFAULT]]
-- procedure: thread-mailbox-rewind
-- procedure: thread-mailbox-extract-and-rewind
To allow a thread to examine the messages in its mailbox without
removing them from the mailbox, each thread has a "mailbox cursor"
which normally points to the last message accessed in the mailbox.
When a mailbox cursor is rewound using the procedure
`thread-mailbox-rewind' or `thread-mailbox-extract-and-rewind' or
`thread-receive', the cursor does not point to a message, but the
next call to `thread-receive' and `thread-mailbox-next' will set
the cursor to the oldest message in the mailbox.
The procedure `thread-receive' advances the mailbox cursor of the
current thread to the next message, removes that message from the
mailbox, rewinds the mailbox cursor, and returns the message. When
TIMEOUT is not specified, the current thread will wait until a
message is available in the mailbox. When TIMEOUT is specified
and DEFAULT is not specified, a mailbox-receive-timeout-exception
object is raised if the timeout is reached before a message is
available. When TIMEOUT is specified and DEFAULT is specified,
DEFAULT is returned if the timeout is reached before a message is
available.
The procedure `thread-mailbox-next' behaves like `thread-receive'
except that the message remains in the mailbox and the mailbox
cursor is not rewound.
The procedures `thread-mailbox-rewind' or
`thread-mailbox-extract-and-rewind' rewind the mailbox cursor of
the current thread so that the next call to `thread-mailbox-next'
and `thread-receive' will access the oldest message in the
mailbox. Additionally the procedure
`thread-mailbox-extract-and-rewind' will remove from the mailbox
the message most recently accessed by a call to
`thread-mailbox-next'. When `thread-mailbox-next' has not been
called since the last call to `thread-receive' or
`thread-mailbox-rewind' or `thread-mailbox-extract-and-rewind', a
call to `thread-mailbox-extract-and-rewind' only resets the mailbox
cursor (no message is removed).
For example:
> (thread-send (current-thread) 111)
> (thread-receive 1 999)
111
> (thread-send (current-thread) 222)
> (thread-send (current-thread) 333)
> (thread-mailbox-next 1 999)
222
> (thread-mailbox-next 1 999)
333
> (thread-mailbox-next 1 999)
999
> (thread-mailbox-extract-and-rewind)
> (thread-receive 1 999)
222
> (thread-receive 1 999)
999
-- procedure: mailbox-receive-timeout-exception? OBJ
-- procedure: mailbox-receive-timeout-exception-procedure EXC
-- procedure: mailbox-receive-timeout-exception-arguments EXC
Mailbox-receive-timeout-exception objects are raised by the
procedures `thread-receive' and `thread-mailbox-next' when a
timeout expires before a message is available and no default value
is specified. The parameter EXC must be a
mailbox-receive-timeout-exception object.
The procedure `mailbox-receive-timeout-exception?' returns `#t'
when OBJ is a mailbox-receive-timeout-exception object and `#f'
otherwise.
The procedure `mailbox-receive-timeout-exception-procedure'
returns the procedure that raised EXC.
The procedure `mailbox-receive-timeout-exception-arguments'
returns the list of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (mailbox-receive-timeout-exception? exc)
(list (mailbox-receive-timeout-exception-procedure exc)
(mailbox-receive-timeout-exception-arguments exc))
'not-mailbox-receive-timeout-exception))
> (with-exception-catcher
handler
(lambda () (thread-receive 1)))
(# (1))
-- procedure: mutex? OBJ
This procedure returns `#t' when OBJ is a mutex object and `#f'
otherwise.
For example:
> (mutex? (make-mutex))
#t
> (mutex? 'foo)
#f
-- procedure: make-mutex [NAME]
This procedure returns a new mutex in the unlocked/not-abandoned
state. The optional NAME is an arbitrary Scheme object which
identifies the mutex (useful for debugging); it defaults to an
unspecified value. The mutex's specific field is set to an
unspecified value.
For example:
> (make-mutex)
#
> (make-mutex 'foo)
#
-- procedure: mutex-name MUTEX
Returns the name of the MUTEX. For example:
> (mutex-name (make-mutex 'foo))
foo
-- procedure: mutex-specific MUTEX
-- procedure: mutex-specific-set! MUTEX OBJ
The `mutex-specific' procedure returns the content of the MUTEX's
specific field.
The `mutex-specific-set!' procedure stores OBJ into the MUTEX's
specific field and returns an unspecified value.
For example:
> (define m (make-mutex))
> (mutex-specific-set! m "hello")
> (mutex-specific m)
"hello"
> (define (mutex-lock-recursively! mutex)
(if (eq? (mutex-state mutex) (current-thread))
(let ((n (mutex-specific mutex)))
(mutex-specific-set! mutex (+ n 1)))
(begin
(mutex-lock! mutex)
(mutex-specific-set! mutex 0))))
> (define (mutex-unlock-recursively! mutex)
(let ((n (mutex-specific mutex)))
(if (= n 0)
(mutex-unlock! mutex)
(mutex-specific-set! mutex (- n 1)))))
> (mutex-lock-recursively! m)
> (mutex-lock-recursively! m)
> (mutex-lock-recursively! m)
> (mutex-specific m)
2
-- procedure: mutex-state MUTEX
Thos procedure returns information about the state of the MUTEX.
The possible results are:
* thread T: the MUTEX is in the locked/owned state and thread T
is the owner of the MUTEX
* symbol `not-owned': the MUTEX is in the locked/not-owned state
* symbol `abandoned': the MUTEX is in the unlocked/abandoned
state
* symbol `not-abandoned': the MUTEX is in the
unlocked/not-abandoned state
For example:
(mutex-state (make-mutex)) ==> not-abandoned
(define (thread-alive? thread)
(let ((mutex (make-mutex)))
(mutex-lock! mutex #f thread)
(let ((state (mutex-state mutex)))
(mutex-unlock! mutex) ; avoid space leak
(eq? state thread))))
-- procedure: mutex-lock! MUTEX [TIMEOUT [THREAD]]
This procedure locks MUTEX. If the MUTEX is currently locked, the
current thread waits until the MUTEX is unlocked, or until the
timeout is reached if TIMEOUT is supplied. If the timeout is
reached, `mutex-lock!' returns `#f'. Otherwise, the state of the
MUTEX is changed as follows:
* if THREAD is `#f' the MUTEX becomes locked/not-owned,
* otherwise, let T be THREAD (or the current thread if THREAD
is not supplied),
* if T is terminated the MUTEX becomes unlocked/abandoned,
* otherwise MUTEX becomes locked/owned with T as the owner.
After changing the state of the MUTEX, an
abandoned-mutex-exception object is raised if the MUTEX was
unlocked/abandoned before the state change, otherwise
`mutex-lock!' returns `#t'. It is not an error if the MUTEX is
owned by the current thread (but the current thread will have to
wait).
For example:
; an implementation of a mailbox object of depth one; this
; implementation does not behave well in the presence of forced
; thread terminations using thread-terminate! (deadlock can occur
; if a thread is terminated in the middle of a put! or get! operation)
(define (make-empty-mailbox)
(let ((put-mutex (make-mutex)) ; allow put! operation
(get-mutex (make-mutex))
(cell #f))
(define (put! obj)
(mutex-lock! put-mutex #f #f) ; prevent put! operation
(set! cell obj)
(mutex-unlock! get-mutex)) ; allow get! operation
(define (get!)
(mutex-lock! get-mutex #f #f) ; wait until object in mailbox
(let ((result cell))
(set! cell #f) ; prevent space leaks
(mutex-unlock! put-mutex) ; allow put! operation
result))
(mutex-lock! get-mutex #f #f) ; prevent get! operation
(lambda (msg)
(case msg
((put!) put!)
((get!) get!)
(else (error "unknown message"))))))
(define (mailbox-put! m obj) ((m 'put!) obj))
(define (mailbox-get! m) ((m 'get!)))
; an alternate implementation of thread-sleep!
(define (sleep! timeout)
(let ((m (make-mutex)))
(mutex-lock! m #f #f)
(mutex-lock! m timeout #f)))
; a procedure that waits for one of two mutexes to unlock
(define (lock-one-of! mutex1 mutex2)
; this procedure assumes that neither mutex1 or mutex2
; are owned by the current thread
(let ((ct (current-thread))
(done-mutex (make-mutex)))
(mutex-lock! done-mutex #f #f)
(let ((t1 (thread-start!
(make-thread
(lambda ()
(mutex-lock! mutex1 #f ct)
(mutex-unlock! done-mutex)))))
(t2 (thread-start!
(make-thread
(lambda ()
(mutex-lock! mutex2 #f ct)
(mutex-unlock! done-mutex))))))
(mutex-lock! done-mutex #f #f)
(thread-terminate! t1)
(thread-terminate! t2)
(if (eq? (mutex-state mutex1) ct)
(begin
(if (eq? (mutex-state mutex2) ct)
(mutex-unlock! mutex2)) ; don't lock both
mutex1)
mutex2))))
-- procedure: mutex-unlock! MUTEX [CONDITION-VARIABLE [TIMEOUT]]
This procedure unlocks the MUTEX by making it
unlocked/not-abandoned. It is not an error to unlock an unlocked
mutex and a mutex that is owned by any thread. If
CONDITION-VARIABLE is supplied, the current thread is blocked and
added to the CONDITION-VARIABLE before unlocking MUTEX; the thread
can unblock at any time but no later than when an appropriate call
to `condition-variable-signal!' or `condition-variable-broadcast!'
is performed (see below), and no later than the timeout (if
TIMEOUT is supplied). If there are threads waiting to lock this
MUTEX, the scheduler selects a thread, the mutex becomes
locked/owned or locked/not-owned, and the thread is unblocked.
`mutex-unlock!' returns `#f' when the timeout is reached,
otherwise it returns `#t'.
NOTE: The reason the thread can unblock at any time (when
CONDITION-VARIABLE is supplied) is that the scheduler, when it
detects a serious problem such as a deadlock, must interrupt one of
the blocked threads (such as the primordial thread) so that it can
perform some appropriate action. After a thread blocked on a
condition-variable has handled such an interrupt it would be wrong
for the scheduler to return the thread to the blocked state,
because any calls to `condition-variable-broadcast!' during the
interrupt will have gone unnoticed. It is necessary for the
thread to remain runnable and return from the call to
`mutex-unlock!' with a result of `#t'.
NOTE: `mutex-unlock!' is related to the "wait" operation on
condition variables available in other thread systems. The main
difference is that "wait" automatically locks MUTEX just after the
thread is unblocked. This operation is not performed by
`mutex-unlock!' and so must be done by an explicit call to
`mutex-lock!'. This has the advantages that a different timeout
and exception-handler can be specified on the `mutex-lock!' and
`mutex-unlock!' and the location of all the mutex operations is
clearly apparent.
For example:
(let loop ()
(mutex-lock! m)
(if (condition-is-true?)
(begin
(do-something-when-condition-is-true)
(mutex-unlock! m))
(begin
(mutex-unlock! m cv)
(loop))))
-- procedure: condition-variable? OBJ
This procedure returns `#t' when OBJ is a condition-variable
object and `#f' otherwise.
For example:
> (condition-variable? (make-condition-variable))
#t
> (condition-variable? 'foo)
#f
-- procedure: make-condition-variable [NAME]
This procedure returns a new empty condition variable. The
optional NAME is an arbitrary Scheme object which identifies the
condition variable (useful for debugging); it defaults to an
unspecified value. The condition variable's specific field is set
to an unspecified value.
For example:
> (make-condition-variable)
#
-- procedure: condition-variable-name CONDITION-VARIABLE
This procedure returns the name of the CONDITION-VARIABLE. For
example:
> (condition-variable-name (make-condition-variable 'foo))
foo
-- procedure: condition-variable-specific CONDITION-VARIABLE
-- procedure: condition-variable-specific-set! CONDITION-VARIABLE OBJ
The `condition-variable-specific' procedure returns the content of
the CONDITION-VARIABLE's specific field.
The `condition-variable-specific-set!' procedure stores OBJ into
the CONDITION-VARIABLE's specific field and returns an unspecified
value.
For example:
> (define cv (make-condition-variable))
> (condition-variable-specific-set! cv "hello")
> (condition-variable-specific cv)
"hello"
-- procedure: condition-variable-signal! CONDITION-VARIABLE
This procedure unblocks a thread blocked on the CONDITION-VARIABLE
(if there is at least one) and returns an unspecified value.
For example:
; an implementation of a mailbox object of depth one; this
; implementation behaves gracefully when threads are forcibly
; terminated using thread-terminate! (an abandoned-mutex-exception
; object will be raised when a put! or get! operation is attempted
; after a thread is terminated in the middle of a put! or get!
; operation)
(define (make-empty-mailbox)
(let ((mutex (make-mutex))
(put-condvar (make-condition-variable))
(get-condvar (make-condition-variable))
(full? #f)
(cell #f))
(define (put! obj)
(mutex-lock! mutex)
(if full?
(begin
(mutex-unlock! mutex put-condvar)
(put! obj))
(begin
(set! cell obj)
(set! full? #t)
(condition-variable-signal! get-condvar)
(mutex-unlock! mutex))))
(define (get!)
(mutex-lock! mutex)
(if (not full?)
(begin
(mutex-unlock! mutex get-condvar)
(get!))
(let ((result cell))
(set! cell #f) ; avoid space leaks
(set! full? #f)
(condition-variable-signal! put-condvar)
(mutex-unlock! mutex))))
(lambda (msg)
(case msg
((put!) put!)
((get!) get!)
(else (error "unknown message"))))))
(define (mailbox-put! m obj) ((m 'put!) obj))
(define (mailbox-get! m) ((m 'get!)))
-- procedure: condition-variable-broadcast! CONDITION-VARIABLE
This procedure unblocks all the thread blocked on the
CONDITION-VARIABLE and returns an unspecified value.
For example:
(define (make-semaphore n)
(vector n (make-mutex) (make-condition-variable)))
(define (semaphore-wait! sema)
(mutex-lock! (vector-ref sema 1))
(let ((n (vector-ref sema 0)))
(if (> n 0)
(begin
(vector-set! sema 0 (- n 1))
(mutex-unlock! (vector-ref sema 1)))
(begin
(mutex-unlock! (vector-ref sema 1) (vector-ref sema 2))
(semaphore-wait! sema))))
(define (semaphore-signal-by! sema increment)
(mutex-lock! (vector-ref sema 1))
(let ((n (+ (vector-ref sema 0) increment)))
(vector-set! sema 0 n)
(if (> n 0)
(condition-variable-broadcast! (vector-ref sema 2)))
(mutex-unlock! (vector-ref sema 1))))
File: gambit-c.info, Node: Dynamic environment, Next: Exceptions, Prev: Threads, Up: Top
14 Dynamic environment
**********************
The "dynamic environment" is the structure which allows the system to
find the value returned by the standard procedures `current-input-port'
and `current-output-port'. The standard procedures
`with-input-from-file' and `with-output-to-file' extend the dynamic
environment to produce a new dynamic environment which is in effect for
the dynamic extent of the call to the thunk passed as their last
argument. These procedures are essentially special purpose dynamic
binding operations on hidden dynamic variables (one for
`current-input-port' and one for `current-output-port'). Gambit
generalizes this dynamic binding mechanism to allow the user to
introduce new dynamic variables, called "parameter objects", and
dynamically bind them. The parameter objects implemented by Gambit are
compatible with the specification of the "Parameter objects SRFI" (SRFI
39).
One important issue is the relationship between the dynamic
environments of the parent and child threads when a thread is created.
Each thread has its own dynamic environment that is accessed when
looking up the value bound to a parameter object by that thread. When
a thread's dynamic environment is extended it does not affect the
dynamic environment of other threads. When a thread is created it is
given a dynamic environment whose bindings are inherited from the
parent thread. In this inherited dynamic environment the parameter
objects are bound to the same cells as the parent's dynamic environment
(in other words an assignment of a new value to a parameter object is
visible in the other thread).
Another important issue is the interaction between the
`dynamic-wind' procedure and dynamic environments. When a thread
creates a continuation, the thread's dynamic environment and the
`dynamic-wind' stack are saved within the continuation (an alternate
but equivalent point of view is that the `dynamic-wind' stack is part
of the dynamic environment). When this continuation is invoked the
required `dynamic-wind' before and after thunks are called and the
saved dynamic environment is reinstated as the dynamic environment of
the current thread. During the call to each required `dynamic-wind'
before and after thunk, the dynamic environment and the `dynamic-wind'
stack in effect when the corresponding `dynamic-wind' was executed are
reinstated. Note that this specification precisely defines the
semantics of calling `call-with-current-continuation' or invoking a
continuation within a before or after thunk. The semantics are well
defined even when a continuation created by another thread is invoked.
Below is an example exercising the subtleties of this semantics.
(with-output-to-file
"foo"
(lambda ()
(let ((k (call-with-current-continuation
(lambda (exit)
(with-output-to-file
"bar"
(lambda ()
(dynamic-wind
(lambda ()
(write '(b1))
(force-output))
(lambda ()
(let ((x (call-with-current-continuation
(lambda (cont) (exit cont)))))
(write '(t1))
(force-output)
x))
(lambda ()
(write '(a1))
(force-output)))))))))
(if k
(dynamic-wind
(lambda ()
(write '(b2))
(force-output))
(lambda ()
(with-output-to-file
"baz"
(lambda ()
(write '(t2))
(force-output)
; go back inside (with-output-to-file "bar" ...)
(k #f))))
(lambda ()
(write '(a2))
(force-output)))))))
The following actions will occur when this code is executed:
`(b1)(a1)' is written to "bar", `(b2)' is then written to "foo", `(t2)'
is then written to "baz", `(a2)' is then written to "foo", and finally
`(b1)(t1)(a1)' is written to "bar".
-- procedure: make-parameter OBJ [FILTER]
The dynamic environment is composed of two parts: the "local
dynamic environment" and the "global dynamic environment". There
is a single global dynamic environment, and it is used to lookup
parameter objects that can't be found in the local dynamic
environment.
The `make-parameter' procedure returns a new "parameter object".
The FILTER argument is a one argument conversion procedure. If it
is not specified, FILTER defaults to the identity function.
The global dynamic environment is updated to associate the
parameter object to a new cell. The initial content of the cell
is the result of applying the conversion procedure to OBJ.
A parameter object is a procedure which accepts zero or one
argument. The cell bound to a particular parameter object in the
dynamic environment is accessed by calling the parameter object.
When no argument is passed, the content of the cell is returned.
When one argument is passed the content of the cell is updated
with the result of applying the parameter object's conversion
procedure to the argument. Note that the conversion procedure can
be used for guaranteeing the type of the parameter object's
binding and/or to perform some conversion of the value.
For example:
> (define radix (make-parameter 10))
> (radix)
10
> (radix 2)
> (radix)
2
> (define prompt
(make-parameter
123
(lambda (x)
(if (string? x)
x
(object->string x)))))
> (prompt)
"123"
> (prompt "$")
> (prompt)
"$"
> (define write-shared
(make-parameter
#f
(lambda (x)
(if (boolean? x)
x
(error "only booleans are accepted by write-shared")))))
> (write-shared 123)
*** ERROR IN ##make-parameter -- only booleans are accepted by write-shared
-- special form: parameterize ((procedure value)...) body
The `parameterize' form, evaluates all procedure and value
expressions in an unspecified order. All the procedure
expressions must evaluate to procedures, either parameter objects
or procedures accepting zero and one argument. Then, for each
procedure p and in an unspecified order:
* If p is a parameter object a new cell is created,
initialized, and bound to the parameter object in the local
dynamic environment. The value contained in the cell is the
result of applying the parameter object's conversion
procedure to value. The resulting dynamic environment is
then used for processing the remaining bindings (or the
evaluation of body if there are no other bindings).
* Otherwise p will be used according to the following protocol:
we say that the call `(p)' "gets p's value" and that the call
`(p x)' "sets p's value to x". First, the `parameterize'
form gets p's value and saves it in a local variable. It
then sets p's value to value. It then processes the
remaining bindings (or evaluates body if there are no other
bindings). Then it sets p's value to the saved value. These
steps are performed in a `dynamic-wind' so that it is
possible to use continuations to jump into and out of the body
(i.e. the `dynamic-wind''s before thunk sets p's value to
value and the after thunk sets p's value to the saved value).
The result(s) of the `parameterize' form are the result(s) of the
body.
Note that using procedures instead of parameter objects may lead to
unexpected results in multithreaded programs because the before and
after thunks of the `dynamic-wind' are not called when control
switches between threads.
For example:
> (define radix (make-parameter 2))
> (define prompt
(make-parameter
123
(lambda (x)
(if (string? x)
x
(object->string x)))))
> (radix)
2
> (parameterize ((radix 16)) (radix))
16
> (radix)
2
> (define (f n) (number->string n (radix)))
> (f 10)
"1010"
> (parameterize ((radix 8)) (f 10))
"12"
> (parameterize ((radix 8) (prompt (f 10))) (prompt))
"1010"
> (define p
(let ((x 1))
(lambda args
(if (null? args) x (set! x (car args))))))
> (let* ((a (p))
(b (parameterize ((p 2)) (list (p))))
(c (p)))
(list a b c))
(1 (2) 1)
File: gambit-c.info, Node: Exceptions, Next: Host environment, Prev: Dynamic environment, Up: Top
15 Exceptions
*************
* Menu:
* Exception-handling:: Exception-handling
* Exception objects related to memory management:: Exception objects related to memory management
* Exception objects related to the host environment:: Exception objects related to the host environment
* Exception objects related to threads:: Exception objects related to threads
* Exception objects related to C-interface:: Exception objects related to C-interface
* Exception objects related to the reader:: Exception objects related to the reader
* Exception objects related to evaluation and compilation:: Exception objects related to evaluation and compilation
* Exception objects related to type checking:: Exception objects related to type checking
* Exception objects related to procedure call:: Exception objects related to procedure call
* Other exception objects:: Other exception objects
File: gambit-c.info, Node: Exception-handling, Next: Exception objects related to memory management, Prev: Exceptions, Up: Exceptions
15.1 Exception-handling
=======================
Gambit's exception-handling model is inspired from the withdrawn
"Exception Handling SRFI" (SRFI 12), the "Multithreading support SRFI"
(SRFI 18), and the "Exception Handling for Programs SRFI" (SRFI 34).
The two fundamental operations are the dynamic binding of an exception
handler (i.e. the procedure `with-exception-handler') and the
invocation of the exception handler (i.e. the procedure `raise').
All predefined procedures which check for errors (including type
errors, memory allocation errors, host operating-system errors, etc)
report these errors using the exception-handling system (i.e. they
"raise" an exception that can be handled in a user-defined exception
handler). When an exception is raised and the exception is not handled
by a user-defined exception handler, the predefined exception handler
will display an error message (if the primordial thread raised the
exception) or the thread will silently terminate with no error message
(if it is not the primordial thread that raised the exception). This
default behavior can be changed through the `-:d' runtime option (*note
Runtime options::).
Predefined procedures normally raise exceptions by performing a
tail-call to the exception handler (the exceptions are "complex"
procedures such as `eval', `compile-file', `read', `write', etc). This
means that the continuation of the exception handler and of the REPL
that may be started due to this is normally the continuation of the
predefined procedure that raised the exception. By exiting the REPL
with the `,(c EXPRESSION)' command it is thus possible to resume the
program as though the call to the predefined procedure returned the
value of EXPRESSION. For example:
> (define (f x) (+ (car x) 1))
> (f 2) ; typo... we meant to say (f '(2))
*** ERROR IN f, (console)@1.18 -- (Argument 1) PAIR expected
(car 2)
1> ,(c 2)
3
-- procedure: current-exception-handler [NEW-EXCEPTION-HANDLER]
The parameter object `current-exception-handler' is bound to the
current exception-handler. Calling this procedure with no argument
returns the current exception-handler and calling this procedure
with one argument sets the current exception-handler to
NEW-EXCEPTION-HANDLER.
For example:
> (current-exception-handler)
#
> (current-exception-handler (lambda (exc) (pp exc) 999))
> (/ 1 0)
#
999
-- procedure: with-exception-handler HANDLER THUNK
Returns the result(s) of calling THUNK with no arguments. The
HANDLER, which must be a procedure, is installed as the current
exception-handler in the dynamic environment in effect during the
call to THUNK. Note that the dynamic environment in effect during
the call to HANDLER has HANDLER as the exception-handler.
Consequently, an exception raised during the call to HANDLER may
lead to an infinite loop.
For example:
> (with-exception-handler
(lambda (e) (write e) 5)
(lambda () (+ 1 (* 2 3) 4)))
11
> (with-exception-handler
(lambda (e) (write e) 5)
(lambda () (+ 1 (* 'foo 3) 4)))
#10
> (with-exception-handler
(lambda (e) (write e 9))
(lambda () (+ 1 (* 'foo 3) 4)))
INFINITE LOOP
-- procedure: with-exception-catcher HANDLER THUNK
Returns the result(s) of calling THUNK with no arguments. A new
exception-handler is installed as the current exception-handler in
the dynamic environment in effect during the call to THUNK. This
new exception-handler will call the HANDLER, which must be a
procedure, with the exception object as an argument and with the
same continuation as the call to `with-exception-catcher'. This
implies that the dynamic environment in effect during the call to
HANDLER is the same as the one in effect at the call to
`with-exception-catcher'. Consequently, an exception raised
during the call to HANDLER will not lead to an infinite loop.
For example:
> (with-exception-catcher
(lambda (e) (write e) 5)
(lambda () (+ 1 (* 2 3) 4)))
11
> (with-exception-catcher
(lambda (e) (write e) 5)
(lambda () (+ 1 (* 'foo 3) 4)))
#5
> (with-exception-catcher
(lambda (e) (write e 9))
(lambda () (+ 1 (* 'foo 3) 4)))
*** ERROR IN (console)@7.1 -- (Argument 2) OUTPUT PORT expected
(write '# 9)
-- procedure: raise OBJ
This procedure tail-calls the current exception-handler with OBJ
as the sole argument. If the exception-handler returns, the
continuation of the call to `raise' is invoked.
For example:
> (with-exception-handler
(lambda (exc)
(pp exc)
100)
(lambda ()
(+ 1 (raise "hello"))))
"hello"
101
-- procedure: abort OBJ
-- procedure: noncontinuable-exception? OBJ
-- procedure: noncontinuable-exception-reason EXC
The procedure `abort' calls the current exception-handler with OBJ
as the sole argument. If the exception-handler returns, the
procedure `abort' will be tail-called with a
noncontinuable-exception object, whose reason field is OBJ, as
sole argument.
Noncontinuable-exception objects are raised by the `abort'
procedure when the exception-handler returns. The parameter EXC
must be a noncontinuable-exception object.
The procedure `noncontinuable-exception?' returns `#t' when OBJ is
a noncontinuable-exception object and `#f' otherwise.
The procedure `noncontinuable-exception-reason' returns the
argument of the call to `abort' that raised EXC.
For example:
> (call-with-current-continuation
(lambda (k)
(with-exception-handler
(lambda (exc)
(pp exc)
(if (noncontinuable-exception? exc)
(k (list (noncontinuable-exception-reason exc)))
100))
(lambda ()
(+ 1 (abort "hello"))))))
"hello"
#
("hello")
File: gambit-c.info, Node: Exception objects related to memory management, Next: Exception objects related to the host environment, Prev: Exception-handling, Up: Exceptions
15.2 Exception objects related to memory management
===================================================
-- procedure: heap-overflow-exception? OBJ
Heap-overflow-exception objects are raised when the allocation of
an object would cause the heap to use more memory space than is
available.
The procedure `heap-overflow-exception?' returns `#t' when OBJ is
a heap-overflow-exception object and `#f' otherwise.
For example:
> (define (handler exc)
(if (heap-overflow-exception? exc)
exc
'not-heap-overflow-exception))
> (with-exception-catcher
handler
(lambda ()
(define (f x) (f (cons 1 x)))
(f '())))
#
-- procedure: stack-overflow-exception? OBJ
Stack-overflow-exception objects are raised when the allocation of
a continuation frame would cause the heap to use more memory space
than is available.
The procedure `stack-overflow-exception?' returns `#t' when OBJ is
a stack-overflow-exception object and `#f' otherwise.
For example:
> (define (handler exc)
(if (stack-overflow-exception? exc)
exc
'not-stack-overflow-exception))
> (with-exception-catcher
handler
(lambda ()
(define (f) (+ 1 (f)))
(f)))
#
File: gambit-c.info, Node: Exception objects related to the host environment, Next: Exception objects related to threads, Prev: Exception objects related to memory management, Up: Exceptions
15.3 Exception objects related to the host environment
======================================================
-- procedure: os-exception? OBJ
-- procedure: os-exception-procedure EXC
-- procedure: os-exception-arguments EXC
-- procedure: os-exception-code EXC
-- procedure: os-exception-message EXC
Os-exception objects are raised by procedures which access the host
operating-system's services when the requested operation fails.
The parameter EXC must be a os-exception object.
The procedure `os-exception?' returns `#t' when OBJ is a
os-exception object and `#f' otherwise.
The procedure `os-exception-procedure' returns the procedure that
raised EXC.
The procedure `os-exception-arguments' returns the list of
arguments of the procedure that raised EXC.
The procedure `os-exception-code' returns an exact integer error
code that can be converted to a string by the `err-code->string'
procedure. Note that the error code is operating-system dependent.
The procedure `os-exception-message' returns `#f' or a string
giving details of the exception in a human-readable form.
For example:
> (define (handler exc)
(if (os-exception? exc)
(list (os-exception-procedure exc)
(os-exception-arguments exc)
(err-code->string (os-exception-code exc))
(os-exception-message exc))
'not-os-exception))
> (with-exception-catcher
handler
(lambda () (host-info "x.y.z")))
(# ("x.y.z") "Unknown host" #f)
-- procedure: no-such-file-or-directory-exception? OBJ
-- procedure: no-such-file-or-directory-exception-procedure EXC
-- procedure: no-such-file-or-directory-exception-arguments EXC
No-such-file-or-directory-exception objects are raised by
procedures which access the filesystem (such as `open-input-file'
and `directory-files') when the path specified can't be found on
the filesystem. The parameter EXC must be a
no-such-file-or-directory-exception object.
The procedure `no-such-file-or-directory-exception?' returns `#t'
when OBJ is a no-such-file-or-directory-exception object and `#f'
otherwise.
The procedure `no-such-file-or-directory-exception-procedure'
returns the procedure that raised EXC.
The procedure `no-such-file-or-directory-exception-arguments'
returns the list of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (no-such-file-or-directory-exception? exc)
(list (no-such-file-or-directory-exception-procedure exc)
(no-such-file-or-directory-exception-arguments exc))
'not-no-such-file-or-directory-exception))
> (with-exception-catcher
handler
(lambda () (with-input-from-file "nofile" read)))
(# ("nofile" #))
-- procedure: unbound-os-environment-variable-exception? OBJ
-- procedure: unbound-os-environment-variable-exception-procedure EXC
-- procedure: unbound-os-environment-variable-exception-arguments EXC
Unbound-os-environment-variable-exception objects are raised when
an unbound operating-system environment variable is accessed by the
procedures `getenv' and `setenv'. The parameter EXC must be an
unbound-os-environment-variable-exception object.
The procedure `unbound-os-environment-variable-exception?' returns
`#t' when OBJ is an unbound-os-environment-variable-exception
object and `#f' otherwise.
The procedure `unbound-os-environment-variable-exception-procedure'
returns the procedure that raised EXC.
The procedure `unbound-os-environment-variable-exception-arguments'
returns the list of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (unbound-os-environment-variable-exception? exc)
(list (unbound-os-environment-variable-exception-procedure exc)
(unbound-os-environment-variable-exception-arguments exc))
'not-unbound-os-environment-variable-exception))
> (with-exception-catcher
handler
(lambda () (getenv "DOES_NOT_EXIST")))
(# ("DOES_NOT_EXIST"))
File: gambit-c.info, Node: Exception objects related to threads, Next: Exception objects related to C-interface, Prev: Exception objects related to the host environment, Up: Exceptions
15.4 Exception objects related to threads
=========================================
-- procedure: scheduler-exception? OBJ
-- procedure: scheduler-exception-reason EXC
Scheduler-exception objects are raised by the scheduler when some
operation requested from the host operating system failed (e.g.
checking the status of the devices in order to wake up threads
waiting to perform I/O on these devices). The parameter EXC must
be a scheduler-exception object.
The procedure `scheduler-exception?' returns `#t' when OBJ is a
scheduler-exception object and `#f' otherwise.
The procedure `scheduler-exception-reason' returns the
os-exception object that describes the failure detected by the
scheduler.
-- procedure: deadlock-exception? OBJ
Deadlock-exception objects are raised when the scheduler discovers
that all threads are blocked and can make no further progress. In
that case the scheduler unblocks the primordial-thread and forces
it to raise a deadlock-exception object.
The procedure `deadlock-exception?' returns `#t' when OBJ is a
deadlock-exception object and `#f' otherwise.
For example:
> (define (handler exc)
(if (deadlock-exception? exc)
exc
'not-deadlock-exception))
> (with-exception-catcher
handler
(lambda () (read (open-vector))))
#
-- procedure: abandoned-mutex-exception? OBJ
Abandoned-mutex-exception objects are raised when the current
thread locks a mutex that was owned by a thread which terminated
(see `mutex-lock!').
The procedure `abandoned-mutex-exception?' returns `#t' when OBJ
is a abandoned-mutex-exception object and `#f' otherwise.
For example:
> (define (handler exc)
(if (abandoned-mutex-exception? exc)
exc
'not-abandoned-mutex-exception))
> (with-exception-catcher
handler
(lambda ()
(let ((m (make-mutex)))
(thread-join!
(thread-start!
(make-thread
(lambda () (mutex-lock! m)))))
(mutex-lock! m))))
#
-- procedure: join-timeout-exception? OBJ
-- procedure: join-timeout-exception-procedure EXC
-- procedure: join-timeout-exception-arguments EXC
Join-timeout-exception objects are raised when a call to the
`thread-join!' procedure reaches its timeout before the target
thread terminates and a timeout-value parameter is not specified.
The parameter EXC must be a join-timeout-exception object.
The procedure `join-timeout-exception?' returns `#t' when OBJ is a
join-timeout-exception object and `#f' otherwise.
The procedure `join-timeout-exception-procedure' returns the
procedure that raised EXC.
The procedure `join-timeout-exception-arguments' returns the list
of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (join-timeout-exception? exc)
(list (join-timeout-exception-procedure exc)
(join-timeout-exception-arguments exc))
'not-join-timeout-exception))
> (with-exception-catcher
handler
(lambda ()
(thread-join!
(thread-start!
(make-thread
(lambda () (thread-sleep! 10))))
5)))
(# (# 5))
-- procedure: started-thread-exception? OBJ
-- procedure: started-thread-exception-procedure EXC
-- procedure: started-thread-exception-arguments EXC
Started-thread-exception objects are raised when the target thread
of a call to the procedure `thread-start!' is already started. The
parameter EXC must be a started-thread-exception object.
The procedure `started-thread-exception?' returns `#t' when OBJ is
a started-thread-exception object and `#f' otherwise.
The procedure `started-thread-exception-procedure' returns the
procedure that raised EXC.
The procedure `started-thread-exception-arguments' returns the
list of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (started-thread-exception? exc)
(list (started-thread-exception-procedure exc)
(started-thread-exception-arguments exc))
'not-started-thread-exception))
> (with-exception-catcher
handler
(lambda ()
(let ((t (make-thread (lambda () (expt 2 1000)))))
(thread-start! t)
(thread-start! t))))
(# (#))
-- procedure: terminated-thread-exception? OBJ
-- procedure: terminated-thread-exception-procedure EXC
-- procedure: terminated-thread-exception-arguments EXC
Terminated-thread-exception objects are raised when the
`thread-join!' procedure is called and the target thread has
terminated as a result of a call to the `thread-terminate!'
procedure. The parameter EXC must be a
terminated-thread-exception object.
The procedure `terminated-thread-exception?' returns `#t' when OBJ
is a terminated-thread-exception object and `#f' otherwise.
The procedure `terminated-thread-exception-procedure' returns the
procedure that raised EXC.
The procedure `terminated-thread-exception-arguments' returns the
list of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (terminated-thread-exception? exc)
(list (terminated-thread-exception-procedure exc)
(terminated-thread-exception-arguments exc))
'not-terminated-thread-exception))
> (with-exception-catcher
handler
(lambda ()
(thread-join!
(thread-start!
(make-thread
(lambda () (thread-terminate! (current-thread))))))))
(# (#))
-- procedure: uncaught-exception? OBJ
-- procedure: uncaught-exception-procedure EXC
-- procedure: uncaught-exception-arguments EXC
-- procedure: uncaught-exception-reason EXC
Uncaught-exception objects are raised when an object is raised in a
thread and that thread does not handle it (i.e. the thread
terminated because it did not catch an exception it raised). The
parameter EXC must be an uncaught-exception object.
The procedure `uncaught-exception?' returns `#t' when OBJ is an
uncaught-exception object and `#f' otherwise.
The procedure `uncaught-exception-procedure' returns the procedure
that raised EXC.
The procedure `uncaught-exception-arguments' returns the list of
arguments of the procedure that raised EXC.
The procedure `uncaught-exception-reason' returns the object that
was raised by the thread and not handled by that thread.
For example:
> (define (handler exc)
(if (uncaught-exception? exc)
(list (uncaught-exception-procedure exc)
(uncaught-exception-arguments exc)
(uncaught-exception-reason exc))
'not-uncaught-exception))
> (with-exception-catcher
handler
(lambda ()
(thread-join!
(thread-start!
(make-thread
(lambda () (open-input-file "data" 99)))))))
(#
(#)
#)
File: gambit-c.info, Node: Exception objects related to C-interface, Next: Exception objects related to the reader, Prev: Exception objects related to threads, Up: Exceptions
15.5 Exception objects related to C-interface
=============================================
-- procedure: cfun-conversion-exception? OBJ
-- procedure: cfun-conversion-exception-procedure EXC
-- procedure: cfun-conversion-exception-arguments EXC
-- procedure: cfun-conversion-exception-code EXC
-- procedure: cfun-conversion-exception-message EXC
Cfun-conversion-exception objects are raised by the C-interface
when converting between the Scheme representation and the C
representation of a value during a call from Scheme to C. The
parameter EXC must be a cfun-conversion-exception object.
The procedure `cfun-conversion-exception?' returns `#t' when OBJ
is a cfun-conversion-exception object and `#f' otherwise.
The procedure `cfun-conversion-exception-procedure' returns the
procedure that raised EXC.
The procedure `cfun-conversion-exception-arguments' returns the
list of arguments of the procedure that raised EXC.
The procedure `cfun-conversion-exception-code' returns an exact
integer error code that can be converted to a string by the
`err-code->string' procedure.
The procedure `cfun-conversion-exception-message' returns `#f' or
a string giving details of the exception in a human-readable form.
For example:
$ cat test1.scm
(define weird
(c-lambda (char-string) nonnull-char-string
"___result = ___arg1;"))
$ gsc test1.scm
$ gsi
Gambit Version 4.0 beta 20
> (load "test1")
"/Users/feeley/gambit/doc/test1.o1"
> (weird "hello")
"hello"
> (define (handler exc)
(if (cfun-conversion-exception? exc)
(list (cfun-conversion-exception-procedure exc)
(cfun-conversion-exception-arguments exc)
(err-code->string (cfun-conversion-exception-code exc))
(cfun-conversion-exception-message exc))
'not-cfun-conversion-exception))
> (with-exception-catcher
handler
(lambda () (weird 'not-a-string)))
(#
(not-a-string)
"(Argument 1) Can't convert to C char-string"
#f)
> (with-exception-catcher
handler
(lambda () (weird #f)))
(#
(#f)
"Can't convert result from C nonnull-char-string"
#f)
-- procedure: sfun-conversion-exception? OBJ
-- procedure: sfun-conversion-exception-procedure EXC
-- procedure: sfun-conversion-exception-arguments EXC
-- procedure: sfun-conversion-exception-code EXC
-- procedure: sfun-conversion-exception-message EXC
Sfun-conversion-exception objects are raised by the C-interface
when converting between the Scheme representation and the C
representation of a value during a call from C to Scheme. The
parameter EXC must be a sfun-conversion-exception object.
The procedure `sfun-conversion-exception?' returns `#t' when OBJ
is a sfun-conversion-exception object and `#f' otherwise.
The procedure `sfun-conversion-exception-procedure' returns the
procedure that raised EXC.
The procedure `sfun-conversion-exception-arguments' returns the
list of arguments of the procedure that raised EXC.
The procedure `sfun-conversion-exception-code' returns an exact
integer error code that can be converted to a string by the
`err-code->string' procedure.
The procedure `sfun-conversion-exception-message' returns `#f' or
a string giving details of the exception in a human-readable form.
For example:
$ cat test2.scm
(c-define (f str) (nonnull-char-string) int "f" ""
(string->number str))
(define t1 (c-lambda () int "___result = f (\"123\");"))
(define t2 (c-lambda () int "___result = f (0);"))
(define t3 (c-lambda () int "___result = f (\"1.5\");"))
$ gsc test2.scm
$ gsi
Gambit Version 4.0 beta 20
> (load "test2")
"/u/feeley/test2.o1"
> (t1)
123
> (define (handler exc)
(if (sfun-conversion-exception? exc)
(list (sfun-conversion-exception-procedure exc)
(sfun-conversion-exception-arguments exc)
(err-code->string (sfun-conversion-exception-code exc))
(sfun-conversion-exception-message exc))
'not-sfun-conversion-exception))
> (with-exception-catcher handler t2)
(#
()
"(Argument 1) Can't convert from C nonnull-char-string"
#f)
> (with-exception-catcher handler t3)
(# () "Can't convert result to C int" #f)
-- procedure: multiple-c-return-exception? OBJ
Multiple-c-return-exception objects are raised by the C-interface
when a C to Scheme procedure call returns and that call's stack
frame is no longer on the C stack because the call has already
returned, or has been removed from the C stack by a `longjump'.
The procedure `multiple-c-return-exception?' returns `#t' when OBJ
is a multiple-c-return-exception object and `#f' otherwise.
For example:
$ cat test3.scm
(c-define (f str) (char-string) scheme-object "f" ""
(pp (list 'entry 'str= str))
(let ((k (call-with-current-continuation (lambda (k) k))))
(pp (list 'exit 'k= k))
k))
(define scheme-to-c-to-scheme-and-back
(c-lambda (char-string) scheme-object
"___result = f (___arg1);"))
$ gsc test3.scm
$ gsi
Gambit Version 4.0 beta 20
> (load "test3")
"/Users/feeley/gambit/doc/test3.o1"
> (define (handler exc)
(if (multiple-c-return-exception? exc)
exc
'not-multiple-c-return-exception))
> (with-exception-catcher
handler
(lambda ()
(let ((c (scheme-to-c-to-scheme-and-back "hello")))
(pp c)
(c 999))))
(entry str= "hello")
(exit k= #)
#
(exit k= 999)
#
File: gambit-c.info, Node: Exception objects related to the reader, Next: Exception objects related to evaluation and compilation, Prev: Exception objects related to C-interface, Up: Exceptions
15.6 Exception objects related to the reader
============================================
-- procedure: datum-parsing-exception? OBJ
-- procedure: datum-parsing-exception-kind EXC
-- procedure: datum-parsing-exception-parameters EXC
-- procedure: datum-parsing-exception-readenv EXC
Datum-parsing-exception objects are raised by the reader (i.e. the
`read' procedure) when the input does not conform to the grammar
for datum. The parameter EXC must be a datum-parsing-exception
object.
The procedure `datum-parsing-exception?' returns `#t' when OBJ is
a datum-parsing-exception object and `#f' otherwise.
The procedure `datum-parsing-exception-kind' returns a symbol
denoting the kind of parsing error that was encountered by the
reader when it raised EXC. Here is a table of the possible return
values:
`datum-or-eof-expected' Datum or EOF expected
`datum-expected' Datum expected
`improperly-placed-dot' Improperly placed dot
`incomplete-form-eof-reached' Incomplete form, EOF reached
`incomplete-form' Incomplete form
`character-out-of-range' Character out of range
`invalid-character-name' Invalid '#\' name
`illegal-character' Illegal character
`s8-expected' Signed 8 bit exact integer
expected
`u8-expected' Unsigned 8 bit exact integer
expected
`s16-expected' Signed 16 bit exact integer
expected
`u16-expected' Unsigned 16 bit exact integer
expected
`s32-expected' Signed 32 bit exact integer
expected
`u32-expected' Unsigned 32 bit exact integer
expected
`s64-expected' Signed 64 bit exact integer
expected
`u64-expected' Unsigned 64 bit exact integer
expected
`inexact-real-expected' Inexact real expected
`invalid-hex-escape' Invalid hexadecimal escape
`invalid-escaped-character' Invalid escaped character
`open-paren-expected' '(' expected
`invalid-token' Invalid token
`invalid-sharp-bang-name' Invalid '#!' name
`duplicate-label-definition' Duplicate definition for label
`missing-label-definition' Missing definition for label
`illegal-label-definition' Illegal definition of label
`invalid-infix-syntax-character' Invalid infix syntax character
`invalid-infix-syntax-number' Invalid infix syntax number
`invalid-infix-syntax' Invalid infix syntax
The procedure `datum-parsing-exception-parameters' returns a list
of the parameters associated with the parsing error that was
encountered by the reader when it raised EXC.
For example:
> (define (handler exc)
(if (datum-parsing-exception? exc)
(list (datum-parsing-exception-kind exc)
(datum-parsing-exception-parameters exc))
'not-datum-parsing-exception))
> (with-exception-catcher
handler
(lambda ()
(with-input-from-string "(s #\\pace)" read)))
(invalid-character-name ("pace"))
File: gambit-c.info, Node: Exception objects related to evaluation and compilation, Next: Exception objects related to type checking, Prev: Exception objects related to the reader, Up: Exceptions
15.7 Exception objects related to evaluation and compilation
============================================================
-- procedure: expression-parsing-exception? OBJ
-- procedure: expression-parsing-exception-kind EXC
-- procedure: expression-parsing-exception-parameters EXC
-- procedure: expression-parsing-exception-source EXC
Expression-parsing-exception objects are raised by the evaluator
and compiler (i.e. the procedures `eval', `compile-file', etc)
when the input does not conform to the grammar for expression. The
parameter EXC must be a expression-parsing-exception object.
The procedure `expression-parsing-exception?' returns `#t' when
OBJ is a expression-parsing-exception object and `#f' otherwise.
The procedure `expression-parsing-exception-kind' returns a symbol
denoting the kind of parsing error that was encountered by the
evaluator or compiler when it raised EXC. Here is a table of the
possible return values:
`id-expected' Identifier expected
`ill-formed-namespace' Ill-formed namespace
`ill-formed-namespace-prefix' Ill-formed namespace prefix
`namespace-prefix-must-be-string' Namespace prefix must be a string
`macro-used-as-variable' Macro name can't be used as a
variable
`ill-formed-macro-transformer' Macro transformer must be a
lambda expression
`reserved-used-as-variable' Reserved identifier can't be used
as a variable
`ill-formed-special-form' Ill-formed special form
`cannot-open-file' Can't open file
`filename-expected' Filename expected
`ill-placed-define' Ill-placed 'define'
`ill-placed-**include' Ill-placed '##include'
`ill-placed-**define-macro' Ill-placed '##define-macro'
`ill-placed-**declare' Ill-placed '##declare'
`ill-placed-**namespace' Ill-placed '##namespace'
`ill-formed-expression' Ill-formed expression
`unsupported-special-form' Interpreter does not support
`ill-placed-unquote' Ill-placed 'unquote'
`ill-placed-unquote-splicing' Ill-placed 'unquote-splicing'
`parameter-must-be-id' Parameter must be an identifier
`parameter-must-be-id-or-default' Parameter must be an identifier
or default binding
`duplicate-parameter' Duplicate parameter in parameter
list
`ill-placed-dotted-rest-parameter' Ill-placed dotted rest parameter
`parameter-expected-after-rest' #!rest must be followed by a
parameter
`ill-formed-default' Ill-formed default binding
`ill-placed-optional' Ill-placed #!optional
`ill-placed-rest' Ill-placed #!rest
`ill-placed-key' Ill-placed #!key
`key-expected-after-rest' #!key expected after rest
parameter
`ill-placed-default' Ill-placed default binding
`duplicate-variable-definition' Duplicate definition of a variable
`empty-body' Body must contain at least one
expression
`variable-must-be-id' Defined variable must be an
identifier
`else-clause-not-last' Else clause must be last
`ill-formed-selector-list' Ill-formed selector list
`duplicate-variable-binding' Duplicate variable in bindings
`ill-formed-binding-list' Ill-formed binding list
`ill-formed-call' Ill-formed procedure call
`ill-formed-cond-expand' Ill-formed 'cond-expand'
`unfulfilled-cond-expand' Unfulfilled 'cond-expand'
The procedure `expression-parsing-exception-parameters' returns a
list of the parameters associated with the parsing error that was
encountered by the evaluator or compiler when it raised EXC.
For example:
> (define (handler exc)
(if (expression-parsing-exception? exc)
(list (expression-parsing-exception-kind exc)
(expression-parsing-exception-parameters exc))
'not-expression-parsing-exception))
> (with-exception-catcher
handler
(lambda ()
(eval '(+ do 1))))
(reserved-used-as-variable (do))
-- procedure: unbound-global-exception? OBJ
-- procedure: unbound-global-exception-variable EXC
-- procedure: unbound-global-exception-code EXC
-- procedure: unbound-global-exception-rte EXC
Unbound-global-exception objects are raised when an unbound global
variable is accessed. The parameter EXC must be an
unbound-global-exception object.
The procedure `unbound-global-exception?' returns `#t' when OBJ is
an unbound-global-exception object and `#f' otherwise.
The procedure `unbound-global-exception-variable' returns a symbol
identifying the unbound global variable.
For example:
> (define (handler exc)
(if (unbound-global-exception? exc)
(list 'variable= (unbound-global-exception-variable exc))
'not-unbound-global-exception))
> (with-exception-catcher
handler
(lambda () foo))
(variable= foo)
File: gambit-c.info, Node: Exception objects related to type checking, Next: Exception objects related to procedure call, Prev: Exception objects related to evaluation and compilation, Up: Exceptions
15.8 Exception objects related to type checking
===============================================
-- procedure: type-exception? OBJ
-- procedure: type-exception-procedure EXC
-- procedure: type-exception-arguments EXC
-- procedure: type-exception-arg-num EXC
-- procedure: type-exception-type-id EXC
Type-exception objects are raised when a primitive procedure is
called with an argument of incorrect type (i.e. when a run time
type-check fails). The parameter EXC must be a type-exception
object.
The procedure `type-exception?' returns `#t' when OBJ is a
type-exception object and `#f' otherwise.
The procedure `type-exception-procedure' returns the procedure
that raised EXC.
The procedure `type-exception-arguments' returns the list of
arguments of the procedure that raised EXC.
The procedure `type-exception-arg-num' returns the position of the
argument whose type is incorrect. Position 1 is the first
argument.
The procedure `type-exception-type-id' returns an identifier of
the type expected. The type-id can be a symbol, such as `number'
and `string-or-nonnegative-fixnum', or a record type descriptor.
For example:
> (define (handler exc)
(if (type-exception? exc)
(list (type-exception-procedure exc)
(type-exception-arguments exc)
(type-exception-arg-num exc)
(type-exception-type-id exc))
'not-type-exception))
> (with-exception-catcher
handler
(lambda () (vector-ref '#(a b c) 'foo)))
(# (#(a b c) foo) 2 exact-integer)
> (with-exception-catcher
handler
(lambda () (time->seconds 'foo)))
(#seconds> (foo) 1 #)
-- procedure: range-exception? OBJ
-- procedure: range-exception-procedure EXC
-- procedure: range-exception-arguments EXC
-- procedure: range-exception-arg-num EXC
Range-exception objects are raised when a numeric parameter is not
in the allowed range. The parameter EXC must be a range-exception
object.
The procedure `range-exception?' returns `#t' when OBJ is a
range-exception object and `#f' otherwise.
The procedure `range-exception-procedure' returns the procedure
that raised EXC.
The procedure `range-exception-arguments' returns the list of
arguments of the procedure that raised EXC.
The procedure `range-exception-arg-num' returns the position of
the argument which is not in the allowed range. Position 1 is the
first argument.
For example:
> (define (handler exc)
(if (range-exception? exc)
(list (range-exception-procedure exc)
(range-exception-arguments exc)
(range-exception-arg-num exc))
'not-range-exception))
> (with-exception-catcher
handler
(lambda () (string-ref "abcde" 10)))
(# ("abcde" 10) 2)
-- procedure: divide-by-zero-exception? OBJ
-- procedure: divide-by-zero-exception-procedure EXC
-- procedure: divide-by-zero-exception-arguments EXC
Divide-by-zero-exception objects are raised when a division by
zero is attempted. The parameter EXC must be a
divide-by-zero-exception object.
The procedure `divide-by-zero-exception?' returns `#t' when OBJ is
a divide-by-zero-exception object and `#f' otherwise.
The procedure `divide-by-zero-exception-procedure' returns the
procedure that raised EXC.
The procedure `divide-by-zero-exception-arguments' returns the
list of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (divide-by-zero-exception? exc)
(list (divide-by-zero-exception-procedure exc)
(divide-by-zero-exception-arguments exc))
'not-divide-by-zero-exception))
> (with-exception-catcher
handler
(lambda () (/ 5 0 7)))
(# (5 0 7))
-- procedure: improper-length-list-exception? OBJ
-- procedure: improper-length-list-exception-procedure EXC
-- procedure: improper-length-list-exception-arguments EXC
-- procedure: improper-length-list-exception-arg-num EXC
Improper-length-list-exception objects are raised by the `map' and
`for-each' procedures when they are called with two or more list
arguments and the lists are not of the same length. The parameter
EXC must be an improper-length-list-exception object.
The procedure `improper-length-list-exception?' returns `#t' when
OBJ is an improper-length-list-exception object and `#f' otherwise.
The procedure `improper-length-list-exception-procedure' returns
the procedure that raised EXC.
The procedure `improper-length-list-exception-arguments' returns
the list of arguments of the procedure that raised EXC.
The procedure `improper-length-list-exception-arg-num' returns the
position of the argument whose length is the shortest. Position 1
is the first argument.
For example:
> (define (handler exc)
(if (improper-length-list-exception? exc)
(list (improper-length-list-exception-procedure exc)
(improper-length-list-exception-arguments exc)
(improper-length-list-exception-arg-num exc))
'not-improper-length-list-exception))
> (with-exception-catcher
handler
(lambda () (map + '(1 2) '(3) '(4 5))))
(# (# (1 2) (3) (4 5)) 3)
File: gambit-c.info, Node: Exception objects related to procedure call, Next: Other exception objects, Prev: Exception objects related to type checking, Up: Exceptions
15.9 Exception objects related to procedure call
================================================
-- procedure: wrong-number-of-arguments-exception? OBJ
-- procedure: wrong-number-of-arguments-exception-procedure EXC
-- procedure: wrong-number-of-arguments-exception-arguments EXC
Wrong-number-of-arguments-exception objects are raised when a
procedure is called with the wrong number of arguments. The
parameter EXC must be a wrong-number-of-arguments-exception object.
The procedure `wrong-number-of-arguments-exception?' returns `#t'
when OBJ is a wrong-number-of-arguments-exception object and `#f'
otherwise.
The procedure `wrong-number-of-arguments-exception-procedure'
returns the procedure that raised EXC.
The procedure `wrong-number-of-arguments-exception-arguments'
returns the list of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (wrong-number-of-arguments-exception? exc)
(list (wrong-number-of-arguments-exception-procedure exc)
(wrong-number-of-arguments-exception-arguments exc))
'not-wrong-number-of-arguments-exception))
> (with-exception-catcher
handler
(lambda () (open-input-file "data" 99)))
(# ("data" 99))
-- procedure: number-of-arguments-limit-exception? OBJ
-- procedure: number-of-arguments-limit-exception-procedure EXC
-- procedure: number-of-arguments-limit-exception-arguments EXC
Number-of-arguments-limit-exception objects are raised by the
`apply' procedure when the procedure being called is passed more
than 8192 arguments. The parameter EXC must be a
number-of-arguments-limit-exception object.
The procedure `number-of-arguments-limit-exception?' returns `#t'
when OBJ is a number-of-arguments-limit-exception object and `#f'
otherwise.
The procedure `number-of-arguments-limit-exception-procedure'
returns the target procedure of the call to `apply' that raised
EXC.
The procedure `number-of-arguments-limit-exception-arguments'
returns the list of arguments of the target procedure of the call
to `apply' that raised EXC.
For example:
> (define (iota n) (if (= n 0) '() (cons n (iota (- n 1)))))
> (define (handler exc)
(if (number-of-arguments-limit-exception? exc)
(list (number-of-arguments-limit-exception-procedure exc)
(length (number-of-arguments-limit-exception-arguments exc)))
'not-number-of-arguments-limit-exception))
> (with-exception-catcher
handler
(lambda () (apply + 1 2 3 (iota 8190))))
(# 8193)
-- procedure: nonprocedure-operator-exception? OBJ
-- procedure: nonprocedure-operator-exception-operator EXC
-- procedure: nonprocedure-operator-exception-arguments EXC
-- procedure: nonprocedure-operator-exception-code EXC
-- procedure: nonprocedure-operator-exception-rte EXC
Nonprocedure-operator-exception objects are raised when a procedure
call is executed and the operator position is not a procedure. The
parameter EXC must be an nonprocedure-operator-exception object.
The procedure `nonprocedure-operator-exception?' returns `#t' when
OBJ is an nonprocedure-operator-exception object and `#f'
otherwise.
The procedure `nonprocedure-operator-exception-operator' returns
the value in operator position of the procedure call that raised
EXC.
The procedure `nonprocedure-operator-exception-arguments' returns
the list of arguments of the procedure call that raised EXC.
For example:
> (define (handler exc)
(if (nonprocedure-operator-exception? exc)
(list (nonprocedure-operator-exception-operator exc)
(nonprocedure-operator-exception-arguments exc))
'not-nonprocedure-operator-exception))
> (with-exception-catcher
handler
(lambda () (11 22 33)))
(11 (22 33))
-- procedure: unknown-keyword-argument-exception? OBJ
-- procedure: unknown-keyword-argument-exception-procedure EXC
-- procedure: unknown-keyword-argument-exception-arguments EXC
Unknown-keyword-argument-exception objects are raised when a
procedure accepting keyword arguments is called and one of the
keywords supplied is not among those that are expected. The
parameter EXC must be an unknown-keyword-argument-exception object.
The procedure `unknown-keyword-argument-exception?' returns `#t'
when OBJ is an unknown-keyword-argument-exception object and `#f'
otherwise.
The procedure `unknown-keyword-argument-exception-procedure'
returns the procedure that raised EXC.
The procedure `unknown-keyword-argument-exception-arguments'
returns the list of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (unknown-keyword-argument-exception? exc)
(list (unknown-keyword-argument-exception-procedure exc)
(unknown-keyword-argument-exception-arguments exc))
'not-unknown-keyword-argument-exception))
> (with-exception-catcher
handler
(lambda () ((lambda (#!key (foo 5)) foo) bar: 11)))
(# (bar: 11))
-- procedure: keyword-expected-exception? OBJ
-- procedure: keyword-expected-exception-procedure EXC
-- procedure: keyword-expected-exception-arguments EXC
Keyword-expected-exception objects are raised when a procedure
accepting keyword arguments is called and a nonkeyword was supplied
where a keyword was expected. The parameter EXC must be an
keyword-expected-exception object.
The procedure `keyword-expected-exception?' returns `#t' when OBJ
is an keyword-expected-exception object and `#f' otherwise.
The procedure `keyword-expected-exception-procedure' returns the
procedure that raised EXC.
The procedure `keyword-expected-exception-arguments' returns the
list of arguments of the procedure that raised EXC.
For example:
> (define (handler exc)
(if (keyword-expected-exception? exc)
(list (keyword-expected-exception-procedure exc)
(keyword-expected-exception-arguments exc))
'not-keyword-expected-exception))
> (with-exception-catcher
handler
(lambda () ((lambda (#!key (foo 5)) foo) 11 22)))
(# (11 22))
File: gambit-c.info, Node: Other exception objects, Prev: Exception objects related to procedure call, Up: Exceptions
15.10 Other exception objects
=============================
-- procedure: error-exception? OBJ
-- procedure: error-exception-message EXC
-- procedure: error-exception-parameters EXC
-- procedure: error MESSAGE OBJ...
Error-exception objects are raised when the `error' procedure is
called. The parameter EXC must be an error-exception object.
The procedure `error-exception?' returns `#t' when OBJ is an
error-exception object and `#f' otherwise.
The procedure `error-exception-message' returns the first argument
of the call to `error' that raised EXC.
The procedure `error-exception-parameters' returns the list of
arguments, starting with the second argument, of the call to
`error' that raised EXC.
The `error' procedure raises an error-exception object whose
message field is MESSAGE and parameters field is the list of
values OBJ....
For example:
> (define (handler exc)
(if (error-exception? exc)
(list (error-exception-message exc)
(error-exception-parameters exc))
'not-error-exception))
> (with-exception-catcher
handler
(lambda () (error "unexpected object:" 123)))
("unexpected object:" (123))
File: gambit-c.info, Node: Host environment, Next: I/O and ports, Prev: Exceptions, Up: Top
16 Host environment
*******************
The host environment is the set of resources, such as the filesystem,
network and processes, that are managed by the operating system within
which the Scheme program is executing. This chapter specifies how the
host environment can be accessed from within the Scheme program.
In this chapter we say that the Scheme program being executed is a
process, even though the concept of process does not exist in some
operating systems supported by Gambit (e.g. MSDOS).
* Menu:
* Handling of file names:: Handling of file names
* Filesystem operations:: Filesystem operations
* Shell command execution:: Shell command execution
* Process termination:: Process termination
* Command line arguments:: Command line arguments
* Environment variables:: Environment variables
* Measuring time:: Measuring time
* File information:: File information
* Group information:: Group information
* User information:: User information .
* Host information:: Host information
* Service information:: Service information
* Protocol information:: Protocol information
* Network information:: Network information
File: gambit-c.info, Node: Handling of file names, Next: Filesystem operations, Prev: Host environment, Up: Host environment
16.1 Handling of file names
===========================
Gambit uses a naming convention for files that is compatible with the
one used by the host environment but extended to allow referring to the
"home directory" of the current user or some specific user and the
"Gambit installation directory".
A "path" is a string that denotes a file, for example
`"src/readme.txt"'. Each component of a path is separated by a `/'
under UNIX and Mac OS X and by a `/' or `\' under MSDOS and Microsoft
Windows. A leading separator indicates an absolute path under UNIX,
Mac OS X, MSDOS and Microsoft Windows. A path which does not contain a
path separator is relative to the "current working directory" on all
operating systems. A volume specifier such as `C:' may prefix a file
name under MSDOS and Microsoft Windows.
The rest of this section uses `/' to represent the path separator.
A path which starts with the characters `~~/' denotes a file in the
Gambit installation directory. This directory is normally
`/usr/local/Gambit-C/version' under UNIX and Mac OS X and
`C:/Gambit-C/version' under MSDOS and Microsoft Windows. To override
this binding under UNIX, Mac OS X, MSDOS and Microsoft Windows, use the
`-:=' runtime option or define the `GAMBCOPT' environment variable.
A path which starts with the characters `~/' denotes a file in the
user's home directory. The user's home directory is contained in the
`HOME' environment variable under UNIX, Mac OS X, MSDOS and Microsoft
Windows. Under MSDOS and Microsoft Windows, if the `HOME' environment
variable is not defined, the environment variables `HOMEDRIVE' and
`HOMEPATH' are concatenated if they are defined. If this fails to
yield a home directory, the Gambit installation directory is used
instead.
A path which starts with the characters `~USERNAME/' denotes a file
in the home directory of the given user. Under UNIX and Mac OS X this
is found using the password file. There is no equivalent under MSDOS
and Microsoft Windows.
-- procedure: current-directory [NEW-CURRENT-DIRECTORY]
The parameter object `current-directory' is bound to the current
working directory. Calling this procedure with no argument returns
the absolute "normalized path" of the directory and calling this
procedure with one argument sets the directory to
NEW-CURRENT-DIRECTORY. The initial binding of this parameter
object is the current working directory of the current process.
The path returned by `current-directory' always contains a trailing
directory separator. Modifications of the parameter object do not
change the current working directory of the current process (i.e.
that is accessible with the UNIX `getcwd()' function and the
Microsoft Windows `GetCurrentDirectory' function). It is an error
to mutate the string returned by `current-directory'.
For example under UNIX:
> (current-directory)
"/Users/feeley/gambit/doc/"
> (current-directory "..")
> (current-directory)
"/Users/feeley/gambit/"
> (path-expand "foo" "~~")
"/usr/local/Gambit-C/4.0b20/foo"
> (parameterize ((current-directory "~~")) (path-expand "foo"))
"/usr/local/Gambit-C/4.0b20/foo"
-- procedure: path-expand PATH [ORIGIN-DIRECTORY]
The procedure `path-expand' takes the path of a file or directory
and returns an expanded path, which is an absolute path when PATH
or ORIGIN-DIRECTORY are absolute paths. The optional
ORIGIN-DIRECTORY parameter, which defaults to the current working
directory, is the directory used to resolve relative paths.
Components of the paths PATH and ORIGIN-DIRECTORY need not exist.
For example under UNIX:
> (path-expand "foo")
"/Users/feeley/gambit/doc/foo"
> (path-expand "~/foo")
"/Users/feeley/foo"
> (path-expand "~~/foo")
"/usr/local/Gambit-C/4.0b20/foo"
> (path-expand "../foo")
"/Users/feeley/gambit/doc/../foo"
> (path-expand "foo" "")
"foo"
> (path-expand "foo" "/tmp")
"/tmp/foo"
> (path-expand "this/file/does/not/exist")
"/Users/feeley/gambit/doc/this/file/does/not/exist"
> (path-expand "")
"/Users/feeley/gambit/doc/"
-- procedure: path-normalize PATH [ALLOW-RELATIVE? [ORIGIN-DIRECTORY]]
The procedure `path-normalize' takes a path of a file or directory
and returns its normalized path. The optional ORIGIN-DIRECTORY
parameter, which defaults to the current working directory, is the
directory used to resolve relative paths. All components of the
paths PATH and ORIGIN-DIRECTORY must exist, except possibly the
last component of PATH. A normalized path is a path containing no
redundant parts and which is consistent with the current structure
of the filesystem. A normalized path of a directory will always
end with a path separator (i.e. `/', `\', or `:' depending on the
operating system). The optional ALLOW-RELATIVE? parameter, which
defaults to `#f', indicates if the path returned can be expressed
relatively to ORIGIN-DIRECTORY: a `#f' requests an absolute path,
the symbol `shortest' requests the shortest of the absolute and
relative paths, and any other value requests the relative path.
The shortest path is useful for interaction with the user because
short relative paths are typically easier to read than long
absolute paths.
For example under UNIX:
> (path-expand "../foo")
"/Users/feeley/gambit/doc/../foo"
> (path-normalize "../foo")
"/Users/feeley/gambit/foo"
> (path-normalize "this/file/does/not/exist")
*** ERROR IN (console)@3.1 -- No such file or directory
(path-normalize "this/file/does/not/exist")
-- procedure: path-extension PATH
-- procedure: path-strip-extension PATH
-- procedure: path-directory PATH
-- procedure: path-strip-directory PATH
-- procedure: path-strip-trailing-directory-separator PATH
-- procedure: path-volume PATH
-- procedure: path-strip-volume PATH
These procedures extract various parts of a path, which need not
be a normalized path. The procedure `path-extension' returns the
file extension (including the period) or the empty string if there
is no extension. The procedure `path-strip-extension' returns the
path with the extension stripped off. The procedure
`path-directory' returns the file's directory (including the last
path separator) or the empty string if no directory is specified
in the path. The procedure `path-strip-directory' returns the
path with the directory stripped off. The procedure
`path-strip-trailing-directory-separator' returns the path with
the directory separator stripped off if one is at the end of the
path. The procedure `path-volume' returns the file's volume
(including the last path separator) or the empty string if no
volume is specified in the path. The procedure
`path-strip-volume' returns the path with the volume stripped off.
For example under UNIX:
> (path-extension "/tmp/foo")
""
> (path-extension "/tmp/foo.txt")
".txt"
> (path-strip-extension "/tmp/foo.txt")
"/tmp/foo"
> (path-directory "/tmp/foo.txt")
"/tmp/"
> (path-strip-directory "/tmp/foo.txt")
"foo.txt"
> (path-strip-trailing-directory-separator "/usr/local/bin/")
"/usr/local/bin"
> (path-strip-trailing-directory-separator "/usr/local/bin")
"/usr/local/bin"
> (path-volume "/tmp/foo.txt")
""
> (path-volume "C:/tmp/foo.txt")
"" ; result is "C:" under Microsoft Windows
> (path-strip-volume "C:/tmp/foo.txt")
"C:/tmp/foo.txt" ; result is "/tmp/foo.txt" under Microsoft Windows
File: gambit-c.info, Node: Filesystem operations, Next: Shell command execution, Prev: Handling of file names, Up: Host environment
16.2 Filesystem operations
==========================
-- procedure: create-directory PATH-OR-SETTINGS
This procedure creates a directory. The argument PATH-OR-SETTINGS
is either a string denoting a filesystem path or a list of port
settings which must contain a `path:' setting. Here are the
settings allowed:
* `path:' STRING
This setting indicates the location of the directory to
create in the filesystem. There is no default value for this
setting.
* `permissions:' 12-BIT-EXACT-INTEGER
This setting controls the UNIX permissions that will be
attached to the file if it is created. The default value of
this setting is `#o777'.
For example:
> (create-directory "newdir")
> (create-directory "newdir")
*** ERROR IN (console)@2.1 -- File exists
(create-directory "newdir")
-- procedure: create-fifo PATH-OR-SETTINGS
This procedure creates a FIFO. The argument PATH-OR-SETTINGS is
either a string denoting a filesystem path or a list of port
settings which must contain a `path:' setting. Here are the
settings allowed:
* `path:' STRING
This setting indicates the location of the FIFO to create in
the filesystem. There is no default value for this setting.
* `permissions:' 12-BIT-EXACT-INTEGER
This setting controls the UNIX permissions that will be
attached to the file if it is created. The default value of
this setting is `#o666'.
For example:
> (create-fifo "fifo")
> (define a (open-input-file "fifo"))
> (define b (open-output-file "fifo"))
> (display "1 22 333" b)
> (force-output b)
> (read a)
1
> (read a)
22
-- procedure: create-link SOURCE-PATH DESTINATION-PATH
This procedure creates a hard link between SOURCE-PATH and
DESTINATION-PATH. The argument SOURCE-PATH must be a string
denoting the path of an existing file. The argument
DESTINATION-PATH must be a string denoting the path of the link to
create.
-- procedure: create-symbolic-link SOURCE-PATH DESTINATION-PATH
This procedure creates a symbolic link between SOURCE-PATH and
DESTINATION-PATH. The argument SOURCE-PATH must be a string
denoting the path of an existing file. The argument
DESTINATION-PATH must be a string denoting the path of the
symbolic link to create.
-- procedure: rename-file SOURCE-PATH DESTINATION-PATH
This procedure renames the file SOURCE-PATH to DESTINATION-PATH.
The argument SOURCE-PATH must be a string denoting the path of an
existing file. The argument DESTINATION-PATH must be a string
denoting the new path of the file.
-- procedure: copy-file SOURCE-PATH DESTINATION-PATH
This procedure copies the file SOURCE-PATH to DESTINATION-PATH.
The argument SOURCE-PATH must be a string denoting the path of an
existing file. The argument DESTINATION-PATH must be a string
denoting the path of the file to create.
-- procedure: delete-file PATH
This procedure deletes the file PATH. The argument PATH must be a
string denoting the path of an existing file.
-- procedure: delete-directory PATH
This procedure deletes the directory PATH. The argument PATH must
be a string denoting the path of an existing directory.
-- procedure: directory-files [PATH-OR-SETTINGS]
This procedure returns the list of the files in a directory. The
argument PATH-OR-SETTINGS is either a string denoting a filesystem
path to a directory or a list of settings which must contain a
`path:' setting. If it is not specified, PATH-OR-SETTINGS
defaults to the current directory (the value bound to the
`current-directory' parameter object). Here are the settings
allowed:
* `path:' STRING
This setting indicates the location of the directory in the
filesystem. There is no default value for this setting.
* `ignore-hidden:' ( `#f' | `#t' | `dot-and-dot-dot' )
This setting controls whether hidden-files will be returned.
Under UNIX and Mac OS X hidden-files are those that start
with a period (such as `.', `..', and `.profile'). Under
Microsoft Windows hidden files are the `.' and `..' entries
and the files whose "hidden file" attribute is set. A
setting of `#f' will enumerate all the files. A setting of
`#t' will only enumerate the files that are not hidden. A
setting of `dot-and-dot-dot' will enumerate all the files
except for the `.' and `..' hidden files. The default value
of this setting is `#t'.
For example:
> (directory-files)
("complex" "README" "simple")
> (directory-files "../include")
("config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")
> (directory-files (list path: "../include" ignore-hidden: #f))
("." ".." "config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")
File: gambit-c.info, Node: Shell command execution, Next: Process termination, Prev: Filesystem operations, Up: Host environment
16.3 Shell command execution
============================
-- procedure: shell-command COMMAND
The procedure `shell-command' calls up the shell to execute
COMMAND which must be a string. This procedure returns the exit
status of the shell in the form that the C library's `system'
routine returns.
For example under UNIX:
> (shell-command "ls -sk f*.scm")
4 fact.scm 4 fib.scm
0
File: gambit-c.info, Node: Process termination, Next: Command line arguments, Prev: Shell command execution, Up: Host environment
16.4 Process termination
========================
-- procedure: exit [STATUS]
The procedure `exit' causes the process to terminate with the
status STATUS which must be an exact integer in the range 0 to
255. If it is not specified, STATUS defaults to 0.
For example under UNIX:
$ gsi
Gambit Version 4.0 beta 20
> (exit 42)
$ echo $?
42
File: gambit-c.info, Node: Command line arguments, Next: Environment variables, Prev: Process termination, Up: Host environment
16.5 Command line arguments
===========================
-- procedure: command-line
This procedure returns a list of strings corresponding to the
command line arguments, including the program file name as the
first element of the list. When the interpreter executes a Scheme
script, the list returned by `command-line' contains the script's
absolute path followed by the remaining command line arguments.
For example under UNIX:
$ gsi -:d -e "(pretty-print (command-line))"
("gsi" "-e" "(pretty-print (command-line))")
$ cat foo
#!/usr/local/Gambit-C/current/bin/gsi-script
(pretty-print (command-line))
$ ./foo 1 2 "3 4"
("/u/feeley/./foo" "1" "2" "3 4")
File: gambit-c.info, Node: Environment variables, Next: Measuring time, Prev: Command line arguments, Up: Host environment
16.6 Environment variables
==========================
-- procedure: getenv NAME [DEFAULT]
-- procedure: setenv NAME [NEW-VALUE]
The procedure `getenv' returns the value of the environment
variable NAME of the current process. Variable names are denoted
with strings. A string is returned if the environment variable is
bound, otherwise DEFAULT is returned if it is specified, otherwise
an exception is raised.
The procedure `setenv' changes the binding of the environment
variable NAME to NEW-VALUE which must be a string. If NEW-VALUE
is not specified the binding is removed.
For example under UNIX:
> (getenv "HOME")
"/Users/feeley"
> (getenv "DOES_NOT_EXIST" #f)
#f
> (setenv "DOES_NOT_EXIST" "it does now")
> (getenv "DOES_NOT_EXIST" #f)
"it does now"
> (setenv "DOES_NOT_EXIST")
> (getenv "DOES_NOT_EXIST" #f)
#f
> (getenv "DOES_NOT_EXIST")
*** ERROR IN (console)@7.1 -- Unbound OS environment variable
(getenv "DOES_NOT_EXIST")