Protecting efficiently a critical section which is mostly read-from and rarely written-into

Viewed 376

I have a multi-threaded application.

It includes a couple of global variables that most of the time are read by several different threads, and very rarely are written by others.

I can protect them with a mutex, but that would be rather "expensive" under these circumstances.

Most of the time, Readers will "lock each other out", the scheduler will intervene if priority inversion is required, etc, etc... All of that without any real need, as reading alone shouldn't do any harm.

So I'm looking for some other type of OS resource that will help me to achieve the goal of protecting these global variables at a lower cost.

The first thing that comes to mind are Counting Semaphores, but I'm not sure how to use them properly in this case, or if they even support what I have in mind... And here is what I have in mind:

  1. A single shared object, called Sem, which supports the following atomic operations:
    • Inc: if count >= 0, increment count; otherwise, lock the calling thread
    • Dec: if count > 0, decrement count and signal all pending threads if count == 0
    • Get: if count == 0, set count = -1; otherwise, lock the calling thread
    • Put: if count == -1, set count = 0 and signal all pending threads
  2. Reader:
    • Sem Inc
    • Read variables
    • Sem Dec
  3. Writer:
    • Sem Get
    • Write variables
    • Sem Put

Of course, the atomic operations are not "for free", as they require disabling the interrupts. Nevertheless, it seems much more efficient than using a mutex, with all the unnecessary additional context-switching which will most likely come along with it.

My questions are as follows:

  1. Is my solution for this problem correct?
    • If yes, what type of OS resource should I use for 'Sem'?
    • If no, where are the pitfalls?
  2. Is this a known problem with a standard solution?

The application is running over ThreadX kernel, but any OS-agnostic answer will be highly appreciated.

4 Answers
Related