试题:
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.
我的回答是(注意:类(class)是基于 Java 的):
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.
我刚刚在纸上记下了上述方法,它似乎有效。
该问题在 20 分问题中值(value) 8 分,因此我怀疑使用 new ReentrantLock(true)
是否足以获得满分。
大家怎么看?
最佳答案
您的回答确实没有解决问题。这不仅与锁定有关,还与排队等待资源的线程有关。
- 如何对等待资源的线程进行排队?
- 如果有线程在等待资源,您如何唤醒它们以便它们按顺序使用资源。
- 如果有线程在等待资源,您如何确保它们按顺序运行并避免围绕新线程抢占它的竞争条件。
一个可能的解决方案类似于下面的代码:
lockResource(resource);
try {
... consume the resource
} finally {
unlockResource(resource);
}
lockResource
会做类似的事情:
- 获取资源锁。
- 检索与包含
long accessNum
和long runningNum
的资源关联的锁对象。 - 增加
accessNum
值并存储线程的结果。 - 检查
long runningNum
值以查看是否 == 到我的accessNum
。 - 如果是==我的,解锁资源并继续运行。
- 如果队列中的人数多于我,请在资源上
wait()
。
当 unlockResource(...)
被调用时,线程应该:
- 锁定资源。
- 设置
运行++
- 调用
notifyAll()
- 解锁资源
如果线程正在等待并被唤醒:
- 检查是否
accessNum == runningNum
。 - 如果为真则解锁资源并继续运行
- 如果没有则返回
wait()
关于java - 共享资源先到先得政策,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11605555/