0

Multiple threads will be “busy waiting” for the next_action variable to be set. Ideally one thread would call perform_action whenever the main sets it to a nonzero.

// choose a time-consuming activity based on action ...

void perform_action(int action);
int next_action = 0;
void* threadfunc(void*)
{
    while (1)
    {
        while (next_action == 0);
        int my_action = next_action;
        next_action = 0;
        perform_action(my_action);
    }
}   
int main()
{
    // assume we've spawned threads executing threadfunc ...
    while (1)
    {
        // determine what action should be dispatched to a thread next
        next_action = read_action_from_user();
        // exit the program
        if (next_action == -1) { break; }
    }
}
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
peter
  • 11
  • 1

1 Answers1

1

For this issue I would use a semaphore. Using a while loop will waste processor time by constantly checking for changes in variable.

Here we can use synchronization methods that can alert when is available.

A semaphore has two options: acquire and release.

  • Main thread initially acquires the semaphore, and the thread is enqueued to acquire it. Thread will wait until semaphore becomes available.
  • When main thread sets it releases the semaphore to signal that a nonzero value has been set to it.
  • The thread will now wake up, acquire the semaphore, perform requested operation and release the semaphore.

  • When main thread needs to change the semaphore, it must acquire the semaphore again, set the and release the semaphore. To acquire the semaphore, main thread must necessarily wait until the thread has finished.

I would not use a mutex because you also need a signaling mechanism to wake up your thread, and not only a protection for a shared variable.

See also Conditional Variable vs Semaphore

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
Marco Frau
  • 109
  • 1
  • 1
  • 11