Пример #1
0
        private Fork GetOrCreateFork(Fork[] forks, int i)
        {
            var fork = forks[i];

            if (fork != null)
            {
                return(fork);
            }

            fork     = new Fork(i);
            forks[i] = fork;
            return(fork);
        }
Пример #2
0
        public Philosopher(Fork left, Fork right, string name)
        {
            _left  = left ?? throw new ArgumentNullException(nameof(left));
            _right = right ?? throw new ArgumentNullException(nameof(right));

            Name = name ?? throw new ArgumentNullException(nameof(name));

            var random = new Random();

            _thinkDurationMs = random.Next(1, MaxThinkDurationMs);
            _eatDurationMs   = random.Next(1, MaxEatDurationMs);

            var thread = new Thread(Start);

            thread.Start();
        }
Пример #3
0
        public DiningTable(int philosopherCount)
        {
            if (philosopherCount < 0)
            {
                throw new ArgumentException("Must be at least 0", nameof(philosopherCount));
            }

            _philosophers = new Philosopher[philosopherCount];
            var forks = new Fork[philosopherCount];

            for (int i = 0; i < _philosophers.Length; i++)
            {
                var forkLeft  = GetOrCreateFork(forks, i > 0 ? i - 1 : philosopherCount - 1);
                var forkRight = GetOrCreateFork(forks, i);

                var philosopher = new Philosopher(forkLeft, forkRight, i.ToString());
                _philosophers[i] = philosopher;
            }
        }