命名互斥体的最佳替代品,以实现每个资源的同步访问
for (int i = 0; i < 100; i++)
{
// If current thread needs resource(i) then
Mutex mutex = new Mutex(false, "Mutex" + i.ToString());
mutex.WaitOne();
// synchronized access to resource(i)
mutex.ReleaseMutex();
}
我们有 100 个资源,每个资源都应该由单个线程并发访问(并发访问资源 [2] 和资源 [5] 是可以的),所以我使用了上面的代码。在这种情况下,命名互斥体的最佳替代方案是什么?
for (int i = 0; i < 100; i++)
{
// If current thread needs resource(i) then
Mutex mutex = new Mutex(false, "Mutex" + i.ToString());
mutex.WaitOne();
// synchronized access to resource(i)
mutex.ReleaseMutex();
}
We have 100 resources and each of them should be accessed by a single thread concurrently (it's OK to access resource[2] and resource[5] concurrently) so I used the above code. What's the best alternative for named mutexes in this scenario?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果这一切都在一个进程中,那么根本不需要命名互斥体。只需创建一个包含 N 个对象的列表或数组并使用
lock
。或者,您可以锁定各个资源对象。如果它们真的是物体的话。我发现使用单独的锁对象更容易理解和维护,因为“资源”可能是一个方法或一组对象。锁对象是一个抽象概念,对我来说有助于理解。
如果多个进程需要这个,那么除了使用互斥体之外,我没有看到更好的解决方案。不过,我建议在程序开始时创建这些
Mutex
对象的列表并保留它们。这样,在循环中您所要做的就是WaitOne
——无需每次在循环中创建对象。If this is all in a single process, then there's no need for named mutexs at all. Just create a list or array of N objects and use
lock
.Alternately, you can lock the individual resource objects. If they really are objects. I've found that using a separate lock object is easier to understand and maintain, because a "resource" might be a method or a group of objects. The lock object is an abstraction that, for me, aids in understanding.
If multiple processes need this, then I don't see a good solution other than using the
Mutex
. However, I'd suggest creating a list of thoseMutex
objects at the start of your program and keeping them around. That way, in the loop all you have to do isWaitOne
--there's no need to create the object each time in the loop.假设资源是引用类的实例,只需锁定每个资源即可。
Assuming resources are instances of reference classes, simply lock each resource.