using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace s { class Program { static Int64 sumValue = 0; static List randomList = new List(); static Semaphore sem = new Semaphore(1, 1); static void AddToResult(int toAdd) { sem.WaitOne(); sumValue += toAdd; sem.Release(); } static void FillList(int Length) { var rand = new Random(); for (int i = 0; i < Length; i++) { randomList.Add(rand.Next(1, 5000)); } } static void PartialSum(int Index, int ToSum) { int sum = 0; int range = Index + ToSum; for (int i = Index; i < range; i++) { sum += randomList[i]; } AddToResult(sum); } static List SetChunk(int AmmontOfThreads) { if (AmmontOfThreads == 0) throw new Exception("Ammount of Threads cannot be zero"); List chunks = new List(); int toCover = randomList.Count; double ch = randomList.Count / AmmontOfThreads; for (int i = 0; i < AmmontOfThreads; i++) { if (i == AmmontOfThreads - 1) { chunks.Add(toCover); } else { int p = (int)Math.Floor(ch); chunks.Add(p); toCover -= p; } } return chunks; } static private List SetIndexes(List Chunks) { var listOfIndex = new List(); int currentIndex = 0; foreach (int chunk in Chunks) { listOfIndex.Add(currentIndex); currentIndex += chunk; } return listOfIndex; } static private List SetThreads(List listOfIndex,List Chunks) { var threadList = new List(); for (int i = 0; i < listOfIndex.Count; i++) { int localIndex = i; var t = new Thread(() => PartialSum(listOfIndex[localIndex], Chunks[localIndex])); t.Start(); threadList.Add(t); } return threadList; } static void Main(string[] args) { const int arraySize = 10000; const int numberOfThreads = 5; var Chunks = SetChunk(10); FillList(arraySize); Chunks = SetChunk(numberOfThreads); List listOfIndex = SetIndexes(Chunks); List threadList = SetThreads(listOfIndex, Chunks); foreach (var t in threadList) t.Join(); Console.WriteLine("WielowÄ…tkowo: "); Console.WriteLine(sumValue); Console.WriteLine("Sekwencyjnie: "); Console.WriteLine(randomList.Sum()); } } }