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.Threading;
- namespace Parallel
- {
- class Program
- {
- internal class SyncResource
- {
- static List<int> Buffer = new List<int>();
- public List<int> Access()
- {
- lock(this) {
- return Buffer;
- }
- }
- public void Write(List<int> password)
- {
- lock(this) {
- Buffer = password;
- }
- }
- }
- //generator haseł
- static IEnumerable<IEnumerable<T>> GetCombinations<T>(IEnumerable<T> list, int length)
- {
- if (length == 1)
- {
- return list.Select(t => new T[] { t });
- }
- return GetCombinations(list, length - 1)
- .SelectMany(t => list, (t1, t2) => t1.Concat(new T[] { t2 }));
- }
- //buffer jednoelementowy
- static SyncResource Buffer = new SyncResource();
- static bool PasswordFound=false;
- /*Ustawianie Bufora
- Zakładamy lock na zmienną, modyfikujemy bufor a następnie informujemy konsumenta o modyfikacji bufora
- zwalniamy lock i czekamy na sygnał*/
- static void SetBuffer(List<int> password)
- {
- Monitor.Enter(Buffer);
- Buffer.Write(password);
- Monitor.Pulse(Buffer);
- Monitor.Wait(Buffer);
- }
- //Czytanie Bufora - zakładamy lock na zmienną, następnie informujemy producenta
- //ze bufor został odczytany, po czym zwalniamy lock
- static List<int> ReadBuffer()
- {
- Monitor.Enter(Buffer);
- var bufferCopy = Buffer.Access();
- return bufferCopy;
- }
- static void Main(string[] args)
- {
- var producent = new Thread(()=>{
- var combinations = GetCombinations<int>(new List<int>{1,2,3,4 },4).ToList();
- foreach(var combination in combinations)
- {
- SetBuffer(combination.ToList());
- if (PasswordFound)
- {
- break;
- }
- }
- Console.WriteLine("Finished Procesing");
- });
- var consumer = new Thread(()=>{
- var password =new List<int>{4,3,2,1};
- do
- {
- var buffer = ReadBuffer();
- if(buffer.SequenceEqual(password))
- {
- PasswordFound=true;
- Console.WriteLine("Password Found");
- }
- Monitor.Pulse(Buffer);
- Monitor.Wait(Buffer);
- }while(!PasswordFound);
- });
- producent.IsBackground=true;
- consumer.IsBackground=true;
- producent.Start();
- consumer.Start();
- Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement