-
-
Save ivanjx/448ea798325527d7fb1863c1566f029d 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; | |
void Produce() | |
{ | |
while (true) | |
{ | |
lock (m_buffer) | |
{ | |
int value = rand.Next(0, 100); | |
if (m_count == BUFFER_SIZE) | |
{ | |
Console.WriteLine("[{0}] Skipped: {1}", m_count, value); | |
} | |
else | |
{ | |
m_buffer[m_count] = value; | |
++m_count; | |
Console.WriteLine("[{0}] Produced.", m_count); | |
} | |
} | |
} | |
} | |
void Consume() | |
{ | |
while (true) | |
{ | |
lock (m_buffer) | |
{ | |
int value = -1; | |
if (m_count > 0) | |
{ | |
value = m_buffer[m_count - 1]; | |
--m_count; | |
} | |
Console.WriteLine("[{0}] Consuming: {1}", m_count, value); | |
} | |
} | |
} | |
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