Advertisement
Guest User

Untitled

a guest
Sep 19th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.18 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5.  
  6. namespace Parallel
  7. {
  8.  
  9.  
  10. class Program
  11. {
  12. internal class SyncResource
  13. {
  14. static List<int> Buffer = new List<int>();
  15. public List<int> Access()
  16. {
  17. lock(this) {
  18. return Buffer;
  19. }
  20. }
  21.  
  22. public void Write(List<int> password)
  23. {
  24. lock(this) {
  25. Buffer = password;
  26. }
  27. }
  28. }
  29. //generator haseł
  30. static IEnumerable<IEnumerable<T>> GetCombinations<T>(IEnumerable<T> list, int length)
  31. {
  32. if (length == 1)
  33. {
  34. return list.Select(t => new T[] { t });
  35. }
  36.  
  37. return GetCombinations(list, length - 1)
  38. .SelectMany(t => list, (t1, t2) => t1.Concat(new T[] { t2 }));
  39. }
  40.  
  41. //buffer jednoelementowy
  42. static SyncResource Buffer = new SyncResource();
  43. static bool PasswordFound=false;
  44.  
  45. /*Ustawianie Bufora
  46. Zakładamy lock na zmienną, modyfikujemy bufor a następnie informujemy konsumenta o modyfikacji bufora
  47. zwalniamy lock i czekamy na sygnał*/
  48. static void SetBuffer(List<int> password)
  49. {
  50. Monitor.Enter(Buffer);
  51.  
  52. Buffer.Write(password);
  53.  
  54. Monitor.Pulse(Buffer);
  55. Monitor.Wait(Buffer);
  56. }
  57.  
  58. //Czytanie Bufora - zakładamy lock na zmienną, następnie informujemy producenta
  59. //ze bufor został odczytany, po czym zwalniamy lock
  60. static List<int> ReadBuffer()
  61. {
  62. Monitor.Enter(Buffer);
  63.  
  64. var bufferCopy = Buffer.Access();
  65.  
  66. return bufferCopy;
  67. }
  68.  
  69.  
  70. static void Main(string[] args)
  71. {
  72. var producent = new Thread(()=>{
  73. var combinations = GetCombinations<int>(new List<int>{1,2,3,4 },4).ToList();
  74.  
  75. foreach(var combination in combinations)
  76. {
  77. SetBuffer(combination.ToList());
  78. if (PasswordFound)
  79. {
  80. break;
  81. }
  82. }
  83. Console.WriteLine("Finished Procesing");
  84. });
  85.  
  86. var consumer = new Thread(()=>{
  87. var password =new List<int>{4,3,2,1};
  88. do
  89. {
  90. var buffer = ReadBuffer();
  91.  
  92. if(buffer.SequenceEqual(password))
  93. {
  94. PasswordFound=true;
  95. Console.WriteLine("Password Found");
  96. }
  97. Monitor.Pulse(Buffer);
  98. Monitor.Wait(Buffer);
  99. }while(!PasswordFound);
  100. });
  101.  
  102.  
  103. producent.IsBackground=true;
  104. consumer.IsBackground=true;
  105.  
  106. producent.Start();
  107. consumer.Start();
  108. Console.ReadLine();
  109.  
  110. }
  111. }
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement