문제

I'm currently trying to implement the Dining Philosopher problem, however I'm running into an issue. I declare my forks as such

public static fixed Monitor forks[5];

however when I try to reference them via

forks[i].Enter();

I'm only given the possibility of "Equals, GetType, ToString, GetHashCode."

Does anyone know how to create an array of Monitors and lock each specific Monitor?

도움이 되었습니까?

해결책

You just need to create an array of objects - you can't create an instance of Monitor; it's a static class. (I'm surprised you can even declare the array - although it's not clear why you've decided to use fixed sized buffers, either. Stick with safe code, I suggest.)

So:

object[] forks = new object[5];
for (int i = 0; i < forks.Length; i++)
{
    forks[i] = new object();
}

Then you can use:

Monitor.Enter(forks[x]);

to acquire the monitor for the index x.

다른 팁

In C#, you can lock on any object, methods on Monitor are static.

So your code should be done this way:

List<object> locks = new List<object>();
for (int i = 0; i < 5; i++) locks.Add(new object());

// ...

Monitor.Enter(locks[0]);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top