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.Runtime.CompilerServices;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace ConsoleApp22
- {
- class Program
- {
- [MethodImpl (MethodImplOptions.Synchronized)]
- public void DoSomething()
- {
- }
- static void Main(string[] args)
- {
- MyCounter c = new MyCounter();
- IncThread myt1 = new IncThread(c);
- DecThread myt2 = new DecThread(c);
- myt1.th.Join();
- myt2.th.Join();
- Console.Read();
- }
- }
- class MyCounter
- {
- private int count = 0;
- private Mutex MuTexLock;
- public MyCounter()
- {
- MuTexLock = new Mutex();
- }
- public Mutex getMutex()
- {
- return MuTexLock;
- }
- public int getCount()
- {
- return count;
- }
- public void setCount(int c)
- {
- count = c;
- }
- }
- class IncThread
- {
- public Thread th;
- private MyCounter c;
- public IncThread(MyCounter c)
- {
- this.c = c;
- th = new Thread(this.Go);
- th.Start();
- }
- void Go()
- {
- Console.WriteLine("IncThread is waiting for the mutex.");
- c.getMutex().WaitOne();
- Console.WriteLine("IncThread acquires the mutex.");
- int num = 10;
- do
- {
- Thread.Sleep(50);
- c.setCount(c.getCount()+1);
- Console.WriteLine("In IncThread, MyCounter.count is " + c.getCount());
- num--;
- } while (num > 0);
- Console.WriteLine("IncThread releases the mutex.");
- c.getMutex().ReleaseMutex();
- }
- }
- class DecThread
- {
- public Thread th;
- private MyCounter c;
- public DecThread(MyCounter c)
- {
- this.c = c;
- th = new Thread(this.Go);
- th.Start();
- }
- void Go()
- {
- Console.WriteLine("DecThread is waiting for the mutex.");
- c.getMutex().WaitOne();
- Console.WriteLine("DecThread acquires the mutex.");
- int num = 10;
- do
- {
- Thread.Sleep(50);
- c.setCount(c.getCount() - 1);
- Console.WriteLine("In DecThread, MyCounter.count is " + c.getCount());
- num--;
- } while (num > 0);
- Console.WriteLine("DecThread releases the mutex.");
- c.getMutex().ReleaseMutex();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement