fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8.  
  9. namespace Test
  10. {
  11. class Program
  12. {
  13. static void Main()
  14. {
  15. var obj1 = new object();
  16. var obj2 = new object();
  17.  
  18. Parallel.For(0, 10, (i) =>
  19. {
  20. var random = new Random(i);
  21.  
  22. for (int j = 0; j < 10; j++)
  23. {
  24. Thread.Sleep(random.Next(0, 100));
  25. MultiLock.Lock((isSuccess) =>
  26. {
  27. Thread.Sleep(random.Next(0, 100));
  28. Console.WriteLine(isSuccess.ToString());
  29. }, TimeSpan.FromMilliseconds(random.Next(0, 100)), obj1, obj2);
  30. }
  31. });
  32. }
  33. }
  34.  
  35. public class MultiLock
  36. {
  37. public static void Lock(Action<bool> callback, TimeSpan timeout, params object[] lockObjects)
  38. {
  39. var sw = Stopwatch.StartNew();
  40.  
  41. for (;;)
  42. {
  43. int count = 0;
  44.  
  45. for (; count < lockObjects.Length; count++)
  46. {
  47. if (!Monitor.TryEnter(lockObjects[count], 0))
  48. {
  49. for (int i = 0; i < count; i++)
  50. {
  51. Monitor.Exit(lockObjects[i]);
  52. }
  53.  
  54. break;
  55. }
  56. }
  57.  
  58. if (count == lockObjects.Length)
  59. {
  60. callback?.Invoke(true);
  61.  
  62. for (int i = 0; i < lockObjects.Length; i++)
  63. {
  64. Monitor.Exit(lockObjects[i]);
  65. }
  66.  
  67. return;
  68. }
  69.  
  70. if (sw.Elapsed > timeout)
  71. {
  72. break;
  73. }
  74.  
  75. Thread.Sleep(100);
  76. }
  77.  
  78. callback?.Invoke(false);
  79. return;
  80. }
  81. }
  82. }
  83.  
Success #stdin #stdout 0.03s 467776KB
stdin
Standard input is empty
stdout
True
True
True
False
True
True
True
True
True
True
True
True
True
True
False
True
False
True
False
False
True
True
False
False
True
True
False
False
True
False
True
False
True
False
False
True
True
False
True
True
True
True
False
True
False
True
True
False
True
True
False
False
True
True
True
False
False
True
False
True
False
True
True
False
True
False
True
False
True
False
True
True
True
True
False
False
True
False
True
True
True
False
False
True
True
False
True
False
True
True
True
False
True
True
True
False
True
True
True
False