Skip to content

Instantly share code, notes, and snippets.

@yutopio
Created March 1, 2018 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yutopio/dff12406968f6f2ca8d641074d64374d to your computer and use it in GitHub Desktop.
Save yutopio/dff12406968f6f2ca8d641074d64374d to your computer and use it in GitHub Desktop.
Producer-Consumer problem implementation
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