An exam question:
A resource is shared between N threads such that access is on a first-come-first-served basis. Explain how you would implement a policy of first-come-first-served.
My answer would be along the lines of (Note: the course is Java-based):
Use a semaphore (binary) to control access to the shared resource. Then create a feeder class/thread to access the semaphore. The feeder thread uses a FIFO queue to implement first-come-first-served. When the semaphore is free it allows the thread a the head of the queue to access the shared resource.
I have just jotted out on paper the above approach and it seems to work.
The question is worth 8 marks in a 20 mark question so I doubt using new ReentrantLock(true) would suffice for full marks.
What do you guys think?
Your answer really doesn’t address the question. This is not just about locking but is also about queuing the threads waiting for the resource.
A possible solution would be something like the following code:
The
lockResourcewould do something like:long accessNumand along runningNum.accessNumvalue and store the results for the thread.long runningNumvalue to see if == to myaccessNum.wait()on resource.When
unlockResource(...)is called, the thread should:running++notifyAll()If a thread is waiting and gets awoken:
accessNum == runningNum.wait()