Search code examples
c#multithreadinglockingbuffering

How can two threads access a common array of buffers with minimal blocking ? (c#)


I'm working on an image processing application where I have two threads on top of my main thread:

1 - CameraThread that captures images from the webcam and writes them into a buffer

2 - ImageProcessingThread that takes the latest image from that buffer for filtering.

The reason why this is multithreaded is because speed is critical and I need to have CameraThread to keep grabbing pictures and making the latest capture ready to pick up by ImageProcessingThread while it's still processing the previous image.

My problem is about finding a fast and thread-safe way to access that common buffer and I've figured that, ideally, it should be a triple buffer (image[3]) so that if ImageProcessingThread is slow, then CameraThread can keep on writing on the two other images and vice versa.

What sort of locking mechanism would be the most appropriate for this to be thread-safe ?

I looked at the lock statement but it seems like it would make a thread block-waiting for another one to be finished and that would be against the point of triple buffering.

Thanks in advance for any idea or advice.

J.


Solution

  • This could be a textbook example of the Producer-Consumer Pattern.

    If you're going to be working in .NET 4, you can use the IProducerConsumerCollection<T> and associated concrete classes to provide your functionality.

    If not, have a read of this article for more information on the pattern, and this question for guidance in writing your own thread-safe implementation of a blocking First-In First-Out structure.