Facebook
From Filip Wicha, 5 Years ago, written in C#.
Embed
Download Paste or View Raw
Hits: 179
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. namespace _2._1._1
  8. {
  9.     class TableOfElements
  10.     {
  11.         private Object thisLock = new Object();
  12.         int[] Arr;
  13.         public int sum = 0;
  14.         Random r = new Random();
  15.  
  16.         public TableOfElements(int length)
  17.         {
  18.             Arr = new int[length];
  19.             for (int i = 0; i < length; i++)
  20.             {
  21.                 Arr[i] = r.Next(-100, 1000);
  22.             }
  23.         }
  24.  
  25.         public void SumArr(int elementNumber)
  26.         {
  27.             lock(thisLock)
  28.             {
  29.                 sum += Arr[elementNumber-1];
  30.                 Console.WriteLine(this.sum);
  31.             }
  32.         }
  33.     }
  34.     class Program
  35.     {
  36.         static void Main(string[] args)
  37.         {
  38.             int n = 4; //number of elements in Array and threads
  39.             TableOfElements tabOfEl = new TableOfElements(n);
  40.  
  41.             Thread[] threads = new Thread[n];
  42.             for (int j = 0; j < n; j++)
  43.             {
  44.                 Thread thread = new Thread(() => tabOfEl.SumArr(j));
  45.                 threads[j] = thread;
  46.             }
  47.             for (int i = 0; i < n; i++)
  48.             {
  49.                 threads[i].Start();
  50.             }
  51.             Thread.Sleep(1000);
  52.             Console.WriteLine("Sum (multithreaded with lock): " + tabOfEl.sum);
  53.             Console.ReadKey();
  54.         }
  55.     }
  56. }
  57.