Hopeless Wanderer
Hopeless Wanderer

Reputation: 23

C program not to allow more than n threads to execute simultaneously a function f

Using locks/condition variables how can you make the structure of a C program not to allow more than n threads to execute simultaneously the body of a function f?Say you have 60 created threads and only 10 are allowed to enter at once in the function. Could you write in pseudocode just as a general idea?

Upvotes: 0

Views: 94

Answers (2)

John Bollinger
John Bollinger

Reputation: 180266

A semaphore, as @zwol suggested, is a good fit for this job:

  • You create the semaphore with its initial value being the number of threads to allow in the function at any given time.
  • The first thing the function does is perform a sem_wait() on the semaphore.
  • You ensure that on every possible code path, the function performs a sem_post() exactly once before returning.

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182769

You need a mutex, a condition variable, and an integer.

  1. Acquire the mutex.
  2. While the integer is 10, block on the condition variable.
  3. Increment the integer.
  4. Release the mutex.
  5. Call the function.
  6. Acquire the mutex.
  7. Decrement the integer.
  8. Broadcast the condition variable.
  9. Release the mutex.

Upvotes: 2

Related Questions