Synchronous concurrency: Difference between revisions

Line 2,243:
Using thread mailboxes for communication between threads:
<lang racket>
;; 1) Read all of the lines of the file "input.txt" and send each line
;; to the Printer thread.
;; 2) Receive the total number of lines printed from the Printer
;; thread and print the value.
(define (reader)
(for ([line (in-lines (open-input-file "input.txt"))])
Line 2,253 ⟶ 2,249:
(printf "Number of lines: ~a\n" (thread-receive)))
 
;; 1) Receive lines from the Reader thread and print each one.
;; 2) Send the total number of lines printed to the Reader thread.
(define (printer)
(thread-send reader-thread
Line 2,261 ⟶ 2,255:
1)))
 
;; Start both threads
(define printer-thread (thread printer))
(define reader-thread (thread reader))
 
;; Wait for both threads to complete
(for-each thread-wait
(list printer-thread reader-thread))
Anonymous user