Skip to content

Instantly share code, notes, and snippets.

@jgreco
Created September 22, 2019 19:41
Show Gist options
  • Save jgreco/a2787f7efeaeab2f8058c669a2cbf454 to your computer and use it in GitHub Desktop.
Save jgreco/a2787f7efeaeab2f8058c669a2cbf454 to your computer and use it in GitHub Desktop.
#lang racket
(require racket/unix-socket)
(define socket-name (format "/tmp/testsock~a" (current-inexact-milliseconds)))
(define (start-socket-server)
(let ([sock-listener (unix-socket-listen socket-name)])
(define (loop)
(let-values ([(in out) (unix-socket-accept sock-listener)])
(thread (thunk
(let loop ()
(write 'tick out) (write "\n" out) (flush-output out)
(sleep 1)
(loop)
))))
(loop))
(thread loop)))
(define (send-to-socket x)
(let-values ([(in out) (unix-socket-connect socket-name)])
(write x out)
(write "\n" out)
(flush-output out)
(read in)))
(define (sync-test)
(define-values (in out) (unix-socket-connect socket-name))
(define syncer
(thread (thunk
(let loop ()
(define receive-evt (thread-receive-evt))
(match (sync in receive-evt)
[(? (curry eq? receive-evt) th)
;; this never happens
(printf "thread-received: ~a~n" (thread-receive))]
[(? input-port? in)
(printf "received from socket: ~a~n" (read in))])
(flush-output)
(loop)))))
(sleep 5)
(thread-send syncer 'foo)
(thread-send syncer 'bar)
(thread-send syncer 'baz)
)
(define (sync-test-alternate)
(define-values (in out) (unix-socket-connect socket-name))
(define thread-syncer
(thread (thunk
(let loop ()
(define receive-evt (thread-receive-evt))
(match (sync receive-evt )
[(? (curry eq? receive-evt) th)
(printf "thread-received: ~a~n" (thread-receive))])
(flush-output)
(loop)))))
(define socket-syncer (thread (thunk
(let loop ()
(match (sync in )
[(? input-port? in)
(printf "received from socket: ~a~n" (read in))])
(flush-output)
(loop)))))
(sleep 5)
(thread-send thread-syncer 'foo)
(thread-send thread-syncer 'bar)
(thread-send thread-syncer 'baz)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment