Skip to content

Commit

Permalink
Q9 - Implement monitors
Browse files Browse the repository at this point in the history
  • Loading branch information
sikatikenmogne committed May 5, 2024
1 parent c35c752 commit 68303d3
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Apply the concepts of threading and synchronization mechanisms to solve practica
6. [x] 6. Implement asynchronous delegates and callback procedures
7. [x] 7. Implement events
8. [x] 8. Implement mutexes
9. [ ] 9. Implement monitors
9. [x] 9. Implement monitors
10. [ ] 10. Implement semaphores
11. [ ] 11. Implement readerWriterLockSlim

Expand Down Expand Up @@ -242,6 +242,9 @@ for (int i = 0; i < 3; i++)
Choose the appropriate core synchronization mechanism (e.g., semaphore).
Implement the mechanism and demonstrate its use with two threads ("T1" and "T2") accessing the shared resource.

#### D. Monitors Implementation:
**💻 [related commit]()**

---
### Q10 - Synchronization:

Expand Down
54 changes: 53 additions & 1 deletion concurency-workshop/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@ internal class Program
// Q7 Evt
private delegate void DELG(object o);

// Q8 Synchronization
// Q8 - Q9 Synchronization
// Define a lock object
private static readonly object lockObject = new object();
private static int var = 0;

// Q9 Synchronization
// private static SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

// <summary>
// Q1 - Delegate* Let the method 'int method (int v1, int v2)'. This method adds two values and returns the result. Write the delegate who will invoke this method
// </summary>
Expand Down Expand Up @@ -332,6 +335,55 @@ static void Main(string[] args)
Console.WriteLine();
// -------------------------------

// <summary>
// Q9 - Synchronization
// </summary>

Console.WriteLine("Q9 - =========Synchronization=========");
Console.WriteLine();

var = 0;

SafeDelegate safeDelegate2 = (object state) =>
{
for (int i = 0; i < 3; i++)
{
bool lockTaken = false;
try
{
Monitor.Enter(lockObject, ref lockTaken);
string name_thread = (string)state;
++var;
Console.WriteLine("Thread -> {0} -- var -> {1}", name_thread, var.ToString());
Thread.Sleep(2000);
}
finally
{
if (lockTaken)
{
Monitor.Exit(lockObject);
}
}
}
};

Thread t6 = new Thread(new ParameterizedThreadStart(safeDelegate2));
Thread t7 = new Thread(new ParameterizedThreadStart(safeDelegate2));

t6.Start("T1");
t7.Start("T2");

t6.Join();
t7.Join();

Console.WriteLine();

Console.WriteLine("Q9 - ==============END=============");

Console.WriteLine();

// -------------------------------

Console.WriteLine("Main thread terminating...");

}
Expand Down

0 comments on commit 68303d3

Please sign in to comment.