1 ;; Simple Actor Machine
3 ;; Houses a population of actors which can communicate using messages
4 ;; with actors on the same machine or other machines via the network.
16 (define (make-machine host port)
18 (define (machine-host m) (car m))
19 (define (machine-port m) (cdr m))
21 (define this-machine (make-machine "localhost" 1234))
23 (define next-actor-id 1)
25 (define (address-id address) (car address))
26 (define (address-machine address) (cdr address))
28 (define (address-local? address)
29 (equal? (address-machine address)
32 (define actor-table (make-hash-table))
34 (define (make-actor beh)
35 (let* ((id next-actor-id))
36 (hash-table-put! id beh)
37 (cons id this-machine)))
39 (define (deliver-message address . message)
40 (let ((id (address-id address)))
41 (let ((behaviour (hash-table-ref/default actor-table id '()))))
43 (print "Warning: discarded message" message " to unknown actor " address)
44 (match (apply (hash-table-ref actor-table id) (cons address message))
45 ('done (hash-table-delete! actor-table actor))
47 (new-beh (hash-table-put! actor new-beh))))))
51 (define local-queue-mutex (make-mutex "message queue"))
52 (define message-available-mutex (make-mutex "message available"))
53 (define local-queue (make-fifo))
55 (define (send-message address . message)
56 (apply (if (address-local? address)
61 (define (send-local-message address . message)
62 (mutex-lock! local-queue-mutex)
63 (fifo-push local-queue (cons address message))
64 (mutex-unlock! local-queue-mutex))
66 (define (send-network-message address . message)
67 (let ((s (udp-open-socket))
68 (machine (address-machine address)))
71 (machine-host machine)
72 (machine-port machine))
74 (udp-close-socket s)))
76 (define (next-local-message)
78 (mutex-lock! local-queue-mutex)
79 (set! res (if (fifo-empty? local-queue)
81 (fifo-pop local-queue)))
82 (mutex-unlock! local-queue-mutex)
85 (define scheduler-thread
88 (let loop ((next-addressed-message (next-local-message)))
89 (if next-addressed-message
90 (apply deliver-message next-addressed-message)