example-06-concurrent-output.scm 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. (import
  2. ;; ports
  3. (ice-9 popen)
  4. (ice-9 textual-ports)
  5. (ice-9 binary-ports)
  6. (ice-9 exceptions)
  7. ;; receive form
  8. ;; (ice-9 receive)
  9. ;; pattern matching
  10. (ice-9 match)
  11. ;; concurrency
  12. (ice-9 threads)
  13. (ice-9 futures)
  14. ;; let-values form
  15. (srfi srfi-11))
  16. (define-values (in out)
  17. (match-let ([(in . out) (pipe)])
  18. ;; make out line buffered
  19. (setvbuf out 'none)
  20. (values in out)))
  21. (define seconds
  22. (λ (s)
  23. (* s (expt 10 6))))
  24. (define endless-writer
  25. (λ (out)
  26. (let loop ()
  27. ;; (simple-format #t "writer: writing message to output port\n")
  28. (put-string out "Hello!\n")
  29. ;; forcing the output should be unnecessary
  30. ;; (force-output out)
  31. (usleep (seconds 1))
  32. (loop))
  33. 'never))
  34. (define reader
  35. (lambda* (in-port #:key (bytes-count 1024) (out-port (current-output-port)))
  36. "Read from an IN-PORT and write to OUT-PORT, BYTES-COUNT
  37. bytes at a time."
  38. (let loop ([bv (get-bytevector-n in-port bytes-count)])
  39. ;; (simple-format #t "reader: reading from in-port\n")
  40. (unless (eof-object? bv)
  41. (put-bytevector out-port bv)
  42. (loop (get-bytevector-n in-port bytes-count))))))
  43. (define line-reader
  44. (lambda* (in-port #:key (out-port (current-output-port)))
  45. "Read from an IN-PORT and write to OUT-PORT."
  46. (let loop ([line (get-line in-port)])
  47. ;; (simple-format #t "reader: reading from in-port\n")
  48. (unless (eof-object? line)
  49. (simple-format out-port "~a\n" line)
  50. ;;(put-string out-port (string-append line "\n"))
  51. (loop (get-line in-port))))))
  52. ;; Start writing and reading endlessly.
  53. (define writer-future (future (endless-writer out)))
  54. (define reader-future (future (line-reader in #:out-port (current-output-port))))
  55. ;; Read from in-port, which should be the corresponding one to the
  56. ;; out-port, to which the endless-writer writes its output. Output to
  57. ;; the current output port, so that the output is visible. Read some
  58. ;; number of bytes at once. Limits the amount of memory needed for the
  59. ;; string.