While I am impatiently awaiting the arrival of my Domino I wanted to test out some code concepts first.
The sensors have an approx 38ms read time (if I am reading the document correctly). If I have multiple sensors, and read them synchronously, then the get readings becomes n * 38ns. Depending on the speed, it can add up if these are mounted on a servo and you are scanning side to side.
So I was trying to work out a framework to do asynchronous readings with a blocking method. This is my first attempt and it seems to work (granted there’s no sensors and I’m randomly generating wait times and sensor readings).
Conceptually, does this make sense in the FEZ world? Is the Mutex too expensive, negating the time savings?
I may have went overboard with mutex wrapping of the array access. But I was thinking that I wanted to make sure that only 1 thread would access the array at a time. Otherwise, I could see 2 threads finishing up at almost the same time and the _signal.Set(); not being called. Eventually there would need to be a timeout in the WaitOne();
static void Main(string[] args)
{
var irsm = new IR.IRSensorManger();
irsm.GetReadings();
Console.WriteLine("....");
irsm.GetReadings();
Console.WriteLine("....");
irsm.GetReadings();
Console.WriteLine("....");
irsm.GetReadings();
Thread.Sleep(Timeout.Infinite);
}
class IRSensorManger
{
AutoResetEvent _signal = new AutoResetEvent(false);
Mutex _arrayMutex = new Mutex();
Random r = new Random();
byte?[] _sensorData = new byte?[3];
Thread sensor1;
Thread sensor2;
Thread sensor3;
void clearSensorData()
{
_arrayMutex.WaitOne();
for (int i = 0; i < _sensorData.Count(); i++)
_sensorData[i] = null;
_arrayMutex.ReleaseMutex();
}
void setSensorData(int index, byte? value)
{
_arrayMutex.WaitOne();
_sensorData[index] = value;
_arrayMutex.ReleaseMutex();
}
byte? getSensorData(int index)
{
_arrayMutex.WaitOne();
byte? val = _sensorData[index];
_arrayMutex.ReleaseMutex();
return val;
}
public void GetReadings()
{
clearSensorData();
sensor1 = new Thread(readSensor);
sensor2 = new Thread(readSensor);
sensor3 = new Thread(readSensor);
sensor1.Start(0);
sensor2.Start(1);
sensor3.Start(2);
Console.WriteLine("Start : " + DateTime.Now.ToString());
_signal.WaitOne();
Console.WriteLine("Finish: " + DateTime.Now.ToString());
}
void readSensor(object data)
{
Thread.Sleep(r.Next(500, 2500));
setSensorData((int)data, (byte)r.Next(0,80));
Console.WriteLine("Thread {0} finished at {1}.{2}", ((int)data).ToString(), DateTime.Now.ToString(), DateTime.Now.Millisecond);
if (getSensorData(0) != null && getSensorData(1) != null && getSensorData(2) != null)
_signal.Set();
}
}
Thanks for any comments