Skip to content

Instantly share code, notes, and snippets.

@ivanjx
Last active May 14, 2021 16:17
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 ivanjx/96409ef9a715e29c781af7e7c2f235c6 to your computer and use it in GitHub Desktop.
Save ivanjx/96409ef9a715e29c781af7e7c2f235c6 to your computer and use it in GitHub Desktop.
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)
{
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)
{
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