Best way to say "terminate unless received by X time"

22 views
Skip to first unread message

David Storrs

unread,
Mar 24, 2020, 4:03:09 PM3/24/20
to Racket Users
I've got this code:

(thread
  (thunk
    (let loop ()
      (define-values (len shost sport) (udp-receive! socket buffer))
      ...do stuff with the received message...
     (loop))))

I'd like to be able to say "If you haven't received a message in X time, kill the thread".  I'm not sure how to enact that; sync/timeout won't do it since the thread won't return.  I've thought of weird signaling systems using channels or set! on some external value or etc, but they are all terrible.

What's the right way to do this?

Jay McCarthy

unread,
Mar 24, 2020, 4:09:55 PM3/24/20
to David Storrs, Racket Users
You can start a second thread that monitors the condition as well as a
timer; if the timer goes off first, then you kill the first thread; if
the condition happens first, then it continues. If you don't want the
second thread to have to monitor the condition, then the first thread
should tell the second thread that everything is okay, such as by
setting a semaphore.

Like this:

```
#lang racket/base

(define (kill-unless-sema-after-secs t sema secs)
(thread
(λ ()
(sync sema
(handle-evt (alarm-evt (+ (current-inexact-milliseconds)
(* 1000 secs)))
(λ _
(kill-thread t)))))))

(module+ main
(define t
(thread
(thunk
(let loop ()
(define sema (make-semaphore))
(kill-unless-sema-after-secs t sema secs)
(define-values (len shost sport)
(udp-receive! socket buffer))
(semaphore-post sema)
;; xxx do stuff
(loop))))))
```

--
Jay McCarthy
Associate Professor @ CS @ UMass Lowell
http://jeapostrophe.github.io
Vincit qui se vincit.
> --
> You received this message because you are subscribed to the Google Groups "Racket Users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to racket-users...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/racket-users/CAE8gKocoTTN0VfOToioMq3xK_0ysqAQVHmZ%2BmiFS9iutzY0sxQ%40mail.gmail.com.

Jon Zeppieri

unread,
Mar 24, 2020, 4:15:51 PM3/24/20
to David Storrs, Racket Users
On Tue, Mar 24, 2020 at 4:03 PM David Storrs <david....@gmail.com> wrote:
>
Not quite sure what you mean when you say "sync/timeout won't do it
since the thread won't return." You'll know when you timed-out, so you
can return in that case. Wouldn't something like this work?

```
(thread
(λ ()
(let loop ()
(match (sync/timeout timeout (udp-receive!-evt socket buffer))
[(list len shost sport)
;; do stuff
(loop)]
[#f
;; timed out; exit the loop and the thread
(void)]))))
```

Apologies if I've misunderstood you.

- Jon

David Storrs

unread,
Mar 24, 2020, 4:23:49 PM3/24/20
to Jon Zeppieri, Racket Users
Aha! I didn't know there was a udp-receive-evt. That's exactly what I needed, thank you.
Reply all
Reply to author
Forward
0 new messages