"Library". The first thread models the reader taking a book. The second thread models the delivery of the book. The number of books in the library is limited. Threads are in different processes.

Tell me, how should it be? I do this:

class Program { static Semaphore semaphoreObj = new Semaphore(4, 5, "my_semaphore"); static void Main(string[] args) { Process.Start(@"C:\visual studio 2015_Projects\4p\bin\Debug\4p.exe"); Thread.Sleep(133); Thread.CurrentThread.Name = "Поток 1"; while (true) Count(); Console.ReadLine(); } public static void Count() { for (int i = 0; i < 1000; i++) { semaphoreObj.WaitOne(); int el; using (FileStream fsr = new FileStream(@"C:\books.txt", FileMode.Open)) using (BinaryReader br = new BinaryReader(fsr)) el = br.ReadInt32(); using (FileStream fsr1 = new FileStream(@"C:\books.txt", FileMode.Open)) using (BinaryWriter bw = new BinaryWriter(fsr1)) { el -= 1; bw.Write(el); } Thread.Sleep(1000); int f = semaphoreObj.Release(); Console.WriteLine("{0} взял книгу. Книг {1}", Thread.CurrentThread.Name, f); } } } } 

So:

  class Program { static Semaphore semaphoreObj; static void Main(string[] args) { semaphoreObj = Semaphore.OpenExisting("my_semaphore"); Thread.CurrentThread.Name = "Поток 2"; while (true) Count(); Console.ReadLine(); } public static void Count() { for (int i = 0; i < 1000; i++) { semaphoreObj.WaitOne(); int el; using (FileStream fsr = new FileStream(@"C:\books.txt", FileMode.Open)) using (BinaryReader br = new BinaryReader(fsr)) el = br.ReadInt32(); using (FileStream fsr1 = new FileStream(@"C:\books.txt", FileMode.Open)) using (BinaryWriter bw = new BinaryWriter(fsr1)) { el += 1; bw.Write(el); } Thread.Sleep(2500); int f=semaphoreObj.Release(); Console.WriteLine("{0} сдал книгу. Книг {1}", Thread.CurrentThread.Name, f); } } } } 

It turns out that the number of books does not change. What is the problem I can not understand ...

  • Eeeee ... And why do you have Process.Start ? You need two threads, not two processes? - VladD
  • Two threads in two different processes - Marchosias
  • Hint: your code reading files is non-working. - andreycha
  • @Marchosias: The condition says nothing about the processes . Are you sure you need processes, not threads? - VladD
  • @andreycha, file reading code to make the thread do something and not just sleep - Marchosias

0