-
-
Save ivanjx/2658a548f02d1a9eab80a421282379d4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.Threading; | |
Random rand = new Random(); | |
const int BUFFER_SIZE = 5; | |
int[] m_buffer = new int[BUFFER_SIZE]; | |
int m_count = 0; | |
Semaphore m_full = new Semaphore(0, BUFFER_SIZE); | |
Semaphore m_empty = new Semaphore(BUFFER_SIZE, BUFFER_SIZE); | |
void Produce() | |
{ | |
while (true) | |
{ | |
int value = rand.Next(0, 100); | |
m_empty.WaitOne(); | |
lock (m_buffer) | |
{ | |
m_buffer[m_count] = value; | |
++m_count; | |
Console.WriteLine("[{0}] Produced.", m_count); | |
} | |
m_full.Release(); | |
} | |
} | |
void Consume() | |
{ | |
while (true) | |
{ | |
m_full.WaitOne(); | |
lock (m_buffer) | |
{ | |
int value = m_buffer[m_count - 1]; | |
--m_count; | |
Console.WriteLine("[{0}] Consuming: {1}", m_count, value); | |
} | |
m_empty.Release(); | |
} | |
} | |
void Main() | |
{ | |
for (int i = 0; i < 4; ++i) | |
{ | |
Thread producer = new Thread(new ThreadStart(Produce)); | |
Thread consumer = new Thread(new ThreadStart(Consume)); | |
producer.Start(); | |
consumer.Start(); | |
} | |
Console.ReadKey(); | |
} | |
Main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment