Created
March 1, 2018 09:24
-
-
Save yutopio/dff12406968f6f2ca8d641074d64374d to your computer and use it in GitHub Desktop.
Producer-Consumer problem implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
class Program | |
{ | |
static int prodIndex = 0; | |
static int consIndex = 0; | |
static Semaphore empty, filled; | |
static string[] buffer; | |
static void Main(string[] args) | |
{ | |
var prod1 = new Thread(Producer); | |
var cons1 = new Thread(Consumer); | |
buffer = new string[20]; | |
empty = new Semaphore(buffer.Length, buffer.Length); | |
filled = new Semaphore(0, buffer.Length); | |
prod1.Start(); | |
cons1.Start(); | |
Thread.Sleep(100000); | |
} | |
static void Producer() | |
{ | |
var id = Thread.CurrentThread.ManagedThreadId; | |
for (var cnt = 0; ;) | |
{ | |
var item = $"{id} @ {++cnt}"; | |
empty.WaitOne(); | |
var i = Interlocked.Increment(ref prodIndex); | |
i = (i - 1) % buffer.Length; | |
buffer[i] = item; | |
filled.Release(); | |
Thread.Sleep(500); | |
} | |
} | |
static void Consumer() | |
{ | |
var id = Thread.CurrentThread.ManagedThreadId; | |
while (true) | |
{ | |
filled.WaitOne(); | |
var i = Interlocked.Increment(ref consIndex); | |
i = (i - 1) % buffer.Length; | |
var item = buffer[i]; | |
empty.Release(); | |
Console.WriteLine($"{id} <-- {item}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment