Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace Threading
- {
- class Program
- {
- private static Mutex mutex = new Mutex();
- private static int Sum = 0;
- static void Main(string[] args)
- {
- Thread[] _workers = new Thread[1000];
- for (int i = 0; i < _workers.Length; i++)
- {
- _workers[i] = new Thread(new ParameterizedThreadStart(MutexDemo));
- _workers[i].Name = string.Format("Thread {0} :", i + 1);
- _workers[i].Start(i);
- }
- foreach (Thread thread in _workers)
- {
- thread.Join();
- }
- Console.WriteLine(Sum);
- Console.ReadKey();
- }
- static void MutexDemo(object custom)
- {
- try
- {
- mutex.WaitOne();
- int i = (int)custom;
- Console.WriteLine("{0} вошел в метод",
- Thread.CurrentThread.Name);
- Console.WriteLine("Сумма до - {0}, i = {1}",Sum,i);
- if (i%2 == 0)
- {
- Sum = Sum + i * 10;
- }
- else
- {
- Sum = Sum - i * 10;
- }
- Thread.Sleep((new Random().Next(1,100)));
- Console.WriteLine("Сумма после - {0}, i = {1}", Sum, i);
- Console.WriteLine("{0} вышел из метода",
- Thread.CurrentThread.Name);
- }
- finally
- {
- mutex.ReleaseMutex();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement