0
votes

Is there a way to make it so I can have n threads run a certain function when other threads are not locking other functions?

I want to achieve something like:

pthread_t threadID[10];
pthread_mutex_t blocking;
pthread_mutex_init(&blocking, NULL);
pthread_cond_t go;
pthread_cond_init(&go, NULL);

void * function1() {
    pthread_mutex_lock(&blocking); // Only one thread at a time!
    // Do some work
    pthread_cond_broadcast(&go);
    pthread_mutex_unlock(&blocking);
}

void * function2() {
    pthread_cond_wait(&go, NULL); // Imagine 5 threads waiting here.
    // Does some work too!
}

What I want is basically that n threads run function2, when no threads are running in function1.

I do not wish to lock function2 as threads may execute it concurrently without a problem, so I know the pthread_cond_wait(&go, NULL) will not work (even the NULL argument is a bit silly). Also, a broadcast will signal all waiting threads, but only one of those threads will make it to the critical code section. I'm aiming to unlock all threads with a signal, and allow all those threads to execute the code.

I know there are ways to do this without going into thread locking mechanisms (like having a variable be modified inside function1 and function2 must check its value before allowing threads to move forward), but I was wondering if there is a way with mutexes and condition variables, not semaphores.

1

1 Answers

1
votes

Yes, this is very easy to do. Use a mutex to protect the shared state, a condition variable when you need to wait for shared state to change, and ordinary integer variables to track the shared state.

When a thread enters a region it should:

  1. Acquire the mutex.
  2. Check if it is allowed to run the region. While not allowed, block on the condition variable while releasing the mutex.
  3. Increment the count of threads in that region.
  4. Release the mutex.

When a thread laves a region it should:

  1. Acquire the mutex.
  2. Decrement the count of threads in that region.
  3. If the change in the count may have allowed a thread to make progress, broadcast the condition variable.
  4. Release the mutex.

It's that simple.