Пример #1
0
        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                studentThreads[i] = new Thread(StudentProblem.Student);
                //studentParams[i].Next = studentParams[i];
                //studentParams[i].Prev = studentParams[i];
                //studentParams[i].Eating = false;
                studentParams[i] = new ThreadParams(i, false);

                studentThreads[i].Start(studentParams[i]);
            }
        }
Пример #2
0
        public static void Student(Object o)
        {
            var r      = new Random();
            var thread = (ThreadParams)o;

            while (true)
            {
                if (!threadsLearning.Contains(thread.Name))
                {
                    Console.WriteLine(" Student " + thread.Name + " start learning.");
                    threadsLearning.Add(thread.Name);
                }

                try
                {
                    toStartLearning.Release();
                    neighboursEating.Release();
                }
                catch
                {
                }

                Thread.Sleep(r.Next(2000, 3000));

                //проверка за свободни вилици (съседите преди и след него)
                //?
                //почва да яде
                //:
                //чака освобождаване на съсед (+1/-1)

                int next = thread.Next;
                if (next == -1)
                {
                    next = 0;
                }

                int prev = thread.Prev;
                if (prev == -1)
                {
                    prev = Program.studentParams.Length - 1;
                }

                ThreadParams nextThread = Program.studentParams[next];
                ThreadParams prevThread = Program.studentParams[prev];

                if (nextThread.Eating || prevThread.Eating)
                {
                    neighboursEating.WaitOne();
                }
                else
                {
                    threadsLearning.Remove(thread.Name);
                    thread.Eating = true;
                    for (int i = 0; i < thread.Name; i++)
                    {
                        Console.Write("_");
                    }
                    Console.WriteLine("> Student " + thread.Name + " start eating.");

                    Thread.Sleep(r.Next(2000, 3000));

                    for (int i = 0; i < thread.Name; i++)
                    {
                        Console.Write("_");
                    }
                    Console.WriteLine("< Student " + thread.Name + " stop eating.");
                    thread.Eating = false;
                    toStartLearning.WaitOne();
                }
            }
        }