Threading in C#
I am hella excited. I am going to attend my first Oklahoma City .NET Users Group meeting on Monday.
Paul Ballard is going to be giving a talk on .NET multi-threading. My last project
was severely multi-threaded, but that was C++/MFC so I thought I would write a small multi-threaded C# program to get a little bit of background.
My last project involved reading data from piece of hardware. These values were floating point values that tended to bounce a bit. I have done very little C#, so I thought I would write a multi-threaded program that would simulate the variance in these values. I figured it would introduce me to random number generation as well as threading, and I am sure I will need random numbers at some point. I am not going to offer much commentary, but here is the code:
using System;
using System.Threading;
namespace CSThreads
{
class Class1
{
// Flag to tell data provider
// thread how long to run
public static bool isRunning;
// The data point of interest
public static double dataPoint;
// Sync's access to the data
// point
public static Mutex myMutex;
[STAThread]
static void Main(string[] args)
{
// Set running flag
isRunning = true;
// Init Mutex
myMutex = new Mutex();
dataPoint = 100.0;
// Data providing thread
Thread myThread = new Thread(
new ThreadStart(
ThreadProc));
// Start the data providing
// thread
myThread.Start();
// Read data from other thread
for (int i = 0; i < 20; ++i)
{
// Wait a bit
Thread.Sleep(500);
// Wait to access resource
// until it is safe
myMutex.WaitOne();
// Retrieve the value
// of interest
double currentValue
= dataPoint;
// Unlock resource
myMutex.ReleaseMutex();
// Give the output
Console.WriteLine("The value
of the data point is
{0}",
currentValue.ToString());
}
// Tell data providing thread
// to terminate
isRunning = false;
}
static void ThreadProc()
{
// Use the number of the beast
// as the initial seed
int i = 43;
// Do until the other
// thread tells us not to
while (isRunning)
{
// Initialize Random object,
// increase seed for variety
Random r = new Random(i++);
// Wait to access resource
// until it is safe
myMutex.WaitOne();
// Generate a random number
// between 95.0 and 105.0
dataPoint = (double)r.Next(
-5000, 5000)/1000.0
+ 100.0;
// Unlock the resource
myMutex.ReleaseMutex();
// Wait a bit
Thread.Sleep(500);
}
}
}
}