Оператор lock и класс Monitor - C#
Формулировка задачи:
Здравствуйте, у меня такая проблема(задача на картинке) мой код прикреплен, надо правильно использовать оператор lock из класса Monitor(как на задании написано) у меня не получается
тема синхронизации потоков
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static int[] AArray;
public class Mas
{ public int[] AArray2;}
static void Min(object o)
{
Mas d = (Mas)o;
int minValue = d.AArray2.Min();
Console.WriteLine("Миниимальное значение: " + minValue);
}
static void Max(object o1)
{
Mas d1 = (Mas)o1;
int maxValue = d1.AArray2.Max();
Console.WriteLine("Максимальное значение: " + maxValue);
}
static int[]Brray()
{
Random rand = new Random();
int[] AArray = new int[100];
for (int i = 0; i < 100; i++)
{
AArray[i] = rand.Next(-50, 50);
Console.WriteLine("{0} элемент: {1}", i, AArray[i]);
}
return AArray;
}
static void Main(string[] args)
{
Console.WriteLine("Задание 3.а");
Console.WriteLine("100 элементов массива:");
var d = new Mas();
var d1 = new Mas();
Brray();
d.AArray2 = AArray;
d1.AArray2 = AArray;
Thread thread1 = new Thread(Min);
Thread thread2 = new Thread(Max);
thread1.Start();
Console.WriteLine("Работа потока 1 завершена");
thread2.Start();
Console.WriteLine("Работа потока 2 завершена");
Console.ReadLine();
}
}
}Решение задачи: «Оператор lock и класс Monitor»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ParallelThreads_Test {
class Program {
static int[] myArray = new int[100];
static EventWaitHandle handle = new AutoResetEvent(false);
static void Main(string[] args) {
Console.WriteLine("Main() started in Thread: {0}", Thread.CurrentThread.ManagedThreadId);
Random r = new Random();
myArray = Enumerable.Range(0, 100).Select(i => r.Next(-50, 51)).ToArray();
PrintArray(myArray);
Parallel.Invoke(
new Action(() => { new Thread(() => { GetMinInt(myArray); }).Start(); }),
new Action(() => { new Thread(() => { GetMaxInt(myArray); }).Start(); }));
Console.ReadLine();
}
static void GetMinInt(int[] arr) {
Console.WriteLine("GetMinInt() started in Thread: {0}", Thread.CurrentThread.ManagedThreadId);
int min = 0;
foreach (int i in arr) {
min = (min > i) ? i : min;
}
handle.WaitOne();
Console.WriteLine("Minimal value is: {0}", min);
}
static void GetMaxInt(int[] arr) {
Console.WriteLine("GetMaxInt() started in Thread: {0}", Thread.CurrentThread.ManagedThreadId);
int max = 0;
foreach (int i in arr) {
max = (max < i) ? i : max;
}
Console.WriteLine("Maximal value is: {0}", max);
handle.Set();
}
static void PrintArray(int[] arr) {
foreach (int i in arr) {
Console.WriteLine("Item: {0}", i);
}
}
}
}