Running 50 threads round robin: semaphores?

I have 50 threads, each of which I want to run a SEGMENT of code, approximately 'fairly', every 200 milli seconds.

Here, 'fairly' means: at any given time, there exists some k, where for each SEGMENT, it has been executed for >= k, <= k+1 times.

One obvious way to do this is to setup each thread as:

worker thread_i
loop {
  acquire semaphore_i;
control thread:
loop {
  for all i: release semahore_i;
  sleep for 200 millis


assume that all tasks complete in 200 millis


question: are there other approaches worth considering ?

You should think about what behavior you want if a worker is unable to keep up. Depending on the answer, you will want either tokio::sync::Notify or tokio::sync::Semaphore or tokio::sync::Barrier.

Strictly speaking based on the >= k, <= k+1 requirement, you should use a Barrier.


A slightly odd requirement! Of course, at 50 threads you're not going to be running them all in parallel, so the os scheduler is already going to kick in. Why not simply do something like:

loop {
  for i in 0..50 {
    tokio::spawn(async {

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.