Вопрос

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