简体   繁体   English

共享和锁定多个线程之间的固定数量资源

[英]Sharing and locking a fixed number resources of between multiple threads

I have a fixed number n of identical resources that need to be shared between n or more threads. 我有一个固定数量n的相同资源,需要在n或多个线程之间共享。 Whenever a thread needs to use a resource, it can take any available one, for which it runs an indetermininate amount of time (ie usage times are not uniform) and then release it. 每当线程需要使用资源时,它可以使用任何可用的资源,为此它运行不确定的时间量(即使用时间不均匀),然后释放它。

What is a good Java data structure to manage this scenario? 管理此场景的优秀Java数据结构是什么? I can only think of one way to do it, which is by using a LinkedBlockingQueue and the take and put operations as locking and releasing a resource, respectively. 我只能想到一种方法,即使用LinkedBlockingQueuetakeput操作分别锁定和释放资源。 I'd just like a suggestion from the concurrency experts: 我只是喜欢并发专家的建议:

For those who are curious: The resources that need to be shared are identical copies of a non-reentrant FORTRAN library for computing multivariate normal CDFs and moments. 对于那些好奇的人:需要共享的资源是用于计算多元正常CDF和时刻的非重入FORTRAN库的相同副本。 Spectacular numerical library, but written in an age where thread-safe code wasn't something to be worried about. 壮观的数字图书馆,但写在一个线程安全代码不值得担心的时代。 In this case we make n copies of the library, where n = Runtime.getRuntime().availableProcessors() . 在这种情况下,我们制作n个库的副本,其中n = Runtime.getRuntime().availableProcessors()

EDIT : I don't want to create the overhead of threads to execute this library. 编辑 :我不想创建执行此库的线程开销。 It is already being called from multiple threads; 它已经从多个线程调用; the calling threads should just be able to lock a resource and get on with it. 调用线程应该能够锁定资源并继续使用它。

UPDATE : See https://stackoverflow.com/a/19039878/586086 for the motivation and the implementation. 更新 :有关动机和实施,请参阅https://stackoverflow.com/a/19039878/586086

The pattern you're describing is a resource pool . 您描述的模式是资源池 A thread-safe queue is a reasonable way to handle the situation when the resources are fairly simple, though you might also consider a pool library such as pool4j . 当资源相当简单时,线程安全队列是处理这种情况的合理方法,尽管您也可以考虑池库,例如pool4j

Create a singleton class with a list of fixed resource, and associated flag to mark each resource as available or unavailable, and 2 synchronized methods, something like: 创建一个包含固定资源列表的单例类,以及将每个资源标记为可用或不可用的关联标志,以及2个同步方法,如:

synchronized Resource getResource(){
   find an unavailable resource, mark it as unavailable and return it
}

synchronized int returnResource(Resource r){
   find the matching resource on list and mark it as available.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM