Advertisement
AyrA

Simple lock mechanism

Mar 19th, 2015
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.34 KB | None | 0 0
  1. //Prints: "SSSSSSSSSSAABABAABABAABABABBBB" (result may vary due to threading)
  2. using System.Threading;
  3. using System;
  4. namespace test
  5. {
  6.     //main class
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             Q q = new Q();
  12.             for (int i = 0; i < 10; i++)
  13.             {
  14.                 Console.Write("S");
  15.                 new Thread(delegate() { q.DoStuff(); }).Start();
  16.             }
  17.             Console.ReadKey(true);
  18.         }
  19.     }
  20.  
  21.     //test class
  22.     public class Q
  23.     {
  24.         private static object lockA;
  25.         private static object lockB;
  26.  
  27.         public Q()
  28.         {
  29.             lockA = new object();
  30.             lockB = new object();
  31.         }
  32.  
  33.         public object DoStuff()
  34.         {
  35.             object result;
  36.             lock (lockA)
  37.             {
  38.                 result=A();
  39.             }
  40.             lock (lockB)
  41.             {
  42.                 return B(result);
  43.             }
  44.         }
  45.  
  46.         private object A()
  47.         {
  48.             //do long work
  49.             Thread.Sleep(2000);
  50.             Console.Write("A");
  51.             return new object();
  52.         }
  53.  
  54.         private object B(object ResultA)
  55.         {
  56.             //do long work
  57.             Thread.Sleep(3000);
  58.             Console.Write("B");
  59.             return new object();
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement