0
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個のリソースがあり、それぞれに1つのスレッドで同時にアクセスする必要があるため(resource[2]とresource[5]に同時にアクセスしても問題ありません)、上記のコードを使用しました。このシナリオでの名前付きミューテックスの最良の代替手段は何ですか?

4

2 に答える 2

2

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.

const int NumLocks = 100;
List<object> LockObjects = new List<object>(NumLocks);

// to initialize
for (int i = 0; i < NumLocks; ++i)
{
    LockObjects.Add(new object());
}

// and your loop
for (int i = 0; i < NumLocks; ++i)
{
    // if current thread needs lock[i] then
    lock(LockObjects[i])
    {
        // do whatever you need to do
        // and then release the 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 those Mutex objects at the start of your program and keeping them around. That way, in the loop all you have to do is WaitOne--there's no need to create the object each time in the loop.

于 2011-04-20T23:29:06.993 に答える
1

リソースが参照クラスのインスタンスであると仮定すると、各リソースを単純にロックします。

var r = resource(i);
lock (r)
{
    // synchronized access to resource(i)
}
于 2011-04-20T23:16:51.447 に答える