So, I am using C on a unix system and have access to the pthreads & semaphore.h libraries.
Here is the problem (I believe this boils down to a “writer priority rw lock” problem):
For simplicities sake, I have two different processes that a thread can run: A & B.
B is more important than A, and thus if there is ever a B waiting to run, I do not want any more A processes to start executing until all of the B processes have run. Additionally, while multiple A processes can run concurrently, only 1 B process can execute at a time.
The current way I am doing this (which I believe to either be wrong, inefficient, or both) is to have the B processes require a lock for their entire execution time and the A processes will acquire and immediately release the lock at the beginning of their execution. I am also using semaphores here to allow for the multi-reader/single writer functionality.
For various reasons, the pthread_rwlock functionality is not usable on this system, so the solution can’t involve them.
If A is going to immediately release the lock, but continue using whatever resource it is that you want to lock, then why do you even bother locking to begin with?
You said:
-Multiple A’s can run simultaneously
-Only one B can run at a time
I’m assuming (but correct me if I’m wrong):
-B and A cannot run at the same time
If you immediately release the lock from A then that’s going to allow a B to run at the same time. Am I missing anything here?
The solution:
Have a mechanism that gets the resource for the a threads. That mechanism only puts a lock on the resource one time when the first A thread starts and releases it only when all A threads are gone.
Have a cancel token for the A threads to use that gets set to true when a B thread begins, then when all A threads have exited the B thread can begin.
The B thread obviously locks and doesn’t release until it’s completed.
Don’t forget to check the cancel token frequently enough in the A thread so that it doesn’t take too long to exit when asked.