Threads waiting for a worker thread to make progress

If anyone would like to help review a little thread synchronization, I have an example.

The motivation:

  • A worker thread updates (set!s) a couple increasing integer variables.

  • Some other threads need to wait until those variables are >= certain values.

  • Instead of the waiters inefficiently busy-looping, I wanted to arrange it so that the worker thread making progress could wake up each waiter when its desired condition is reached.

  • Note: The values always increase, so if a condition becomes true, it remains true. Which I think simplifies this a little.

The least-worst thing I was able to come up with so far:

This performs well (enough for my benchmarks) and has no bugs (that I've discovered yet).

But I can't help wondering if I'm:

  • Overlooking some other, better way to do this in Racket?

  • Re-inventing some wheel? (This feels vaguely like so-called "condition variables" but I have zero hands-on mileage with that; from what I've read so far that feels more general than what I need here.)

3 Likes

I'm a fan of channels and threads myself.

(Lightly tested) counter.rkt · GitHub

2 Likes

Thanks I'll take a look at that.

I'm a fan of channels and threads myself.

Me, too! Channels are usually where I start, and nearly as often where I end up.

Although the example code shows it, I didn't really call out one aspect: There won't be a waiter interested in every -- or even most! -- progress updates.

For example some waiter might want to know when a counter reaches at least 5, but nothing before or after.

As a result, I assumed it would be wasteful to dump every single progress update into a channel?

Instead I figured the worker/updater should check a list of predicates, and IFF any became satisfied, alert/wake a waiter. Since there's no value to communicate except "hey your condition was met", I figured a semaphore would suffice. But a channel with a #t value could work for that instead.