This is the mail archive of the guile@cygnus.com mailing list for the guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Threads versus event loop


"ccf::satchell"@hermes.dra.hmg.gb writes:

> What do people on the list think is best approach? There is 
> limited documentation about the thread system, and most of that is
> marked as

If you want to solve it with threads, the following code could be
useful as an example of how to spawn servers.  You must use a recent
snapshot of Guile for it to work.  (It won't do with Guile-1.2.)

/mdj

;;;; 	Copyright (C) 1997 Free Software Foundation, Inc.
;;;; 
;;;; This program is free software; you can redistribute it and/or modify
;;;; it under the terms of the GNU General Public License as published by
;;;; the Free Software Foundation; either version 2, or (at your option)
;;;; any later version.
;;;; 
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;;; GNU General Public License for more details.
;;;; 
;;;; You should have received a copy of the GNU General Public License
;;;; along with this software; see the file COPYING.  If not, write to
;;;; the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;; 

;;; This file implements a simple Guile server.
;;;
;;; It enables a Guile interpreter to work as a server, supplying
;;; multiple repl sessions, each running in its own thread.
;;;
;;; Load this file into a Guile running on machine x.y.z.w and type
;;;
;;;   (server)
;;;
;;; Then type
;;;
;;;   telnet x.y.z.w 20003
;;;
;;; at the shell prompt.  ("x.y.z.w" can be replaced by "localhost" if
;;; telnet is running on the same machine as the interpreter.)
;;;
;;; Use `(quit)' at the telnet (Guile) prompt to close down a
;;; connection.
;;;
;;; BUGS: Currently, signals (like interrupt) don't work.
;;;

(define server-port 20003)

(define (server-report action conn p)
  (display (strftime "%y%m%d %H:%M:%S: " (localtime (current-time))) p)
  (display action p)
  (display " connection from " p)
  (display (inet-ntoa (vector-ref conn 1)) p)
  (display " at port " p)
  (display (vector-ref conn 2) p)
  (newline p))

(define (server)
  (let ((o (current-output-port))
	(port (socket AF_INET SOCK_STREAM 0)))
    (bind port AF_INET INADDR_ANY server-port)
    (listen port 10)			; Queue up to 10 requests.
    (let loop ()
      (select (list port) () ())
      (let ((p (accept port)))
	(begin-thread
	 (server-report "Opening" (cdr p) o)
	 (server-repl (car p))
	 (server-report "Closing" (cdr p) o)
	 (close-port (car p))))
      (loop))))

(define (server-repl p)
  (set-current-input-port p)
  (set-current-output-port p)
  (set-current-error-port p)
  (top-repl))