I’m cleaning up some code in the hopes of incorporating some of the things I’ve learned in the past months and it has become apparent I don’t really understand how locks work.
Most of my apps have to read data from a lot of sensors. Many of these sensors are RS232 and I use an event handler for each sensor’s serial port to grab the bytes as the sensor sends them. Once I get a complete message I put in in “my” queue (that I modified from @ taylorza’s class). In the future other threads may want to use the queue so I’m trying to use locks to make everything thread safe.
My 2 basic questions are 1) does every class in every thread that needs to enqueue something need it’s own lock defined in the class and 2) Where do I put the locks?
In my current implementation, each sensor generally has it’s own class and it’s own lock defined like this:
Is that right or should I use one global lock object or ?.
Then when that class' event handler (or any other method in that class ) needs to enqueue something it does this:
```cs]lock (GPSLock) { Program.sQueue.Enqueue(qS); }[/code
The Enqueue method is pretty simple. Should I lock it also? Or lock it instead of locking the calls to it?
```cs
public void Enqueue(qStruct inStruct)
{
if (count >= qDepth)
{
throw new InvalidOperationException("Queue is full");
}
else
{
queue[head].qRecordType = inStruct.qRecordType;
queue[head].timeStamp = inStruct.timeStamp;
queue[head].state = inStruct.state;
Array.Copy(inStruct.byteArray, queue[head].byteArray, inStruct.byteArray.Length);
head = (head + 1) % qDepth;
count++;
}
}
Looking forward to your suggestions.