Sherif elKhatib
Sherif elKhatib

Reputation: 45942

Threading: Shared Resource special situation

I have a certain resource that can be used by two types of tasks: Normal Task which is run by many different threads simultaneously and Special Task which is run rarely by a single thread.

My objectives are:

  1. All the Normal Tasks should be able to access this resource normally except if the Special Task is running.
  2. The Special Task should also wait until this resource is free (from any Normal Task that might be running).
  3. If the Special Task is not running, Normal Tasks should be able to use this resource simultaneously (it is thread safe).

To be precise, I have one Rabbit-MQ queue that is accessed by this resource to pop messages. Any of the users calling my webservice can use this resource (pop a message) simultaneously. However, I have a special function that purges the queue and refills it with messages from the DB.

My challenge is locking the object only with respect to this special task but at the same time allowing normal tasks to use it concurrently.

Upvotes: 0

Views: 17

Answers (1)

Philipp Wendler
Philipp Wendler

Reputation: 11433

Your objectives sound exactly like the use case of a ReadWriteLock, which allows only one writer, but arbitrary readers if there is no writer. The Special Task can take a write lock, all other tasks a read lock.

Upvotes: 2

Related Questions