views:

550

answers:

2

I am writing a program using .Net 3.5 and OpenCV 1.1. I have multiple threads that need to get an image variables from the web camera on my computer, the problem being I get memory violation errors when multiple threads try to access the camera at the same time. I know I can use PostThreadMessage and GetMessage to send a variable to the threads. Can anyone give me a tutorial or example of how to pass a variable to a thread while it is running using PostThreadMessage and GetMessage?

The errors I get are memory access violation errors, when both of my worker threads try to call a function that gets an image from the camera. I want to get around this by having one thread get the images for all of the others. They each have their one IplImage variable that stores the image captured by the camera. Hope this helps.

A: 

Where are the memory errors occurring? Can you post some more detail? Are they occurring during accesses to your data structures, or to OpenCV ones? If it's the latter, then I am not sure how messaging is going to help. In either case, a little bit of locking around non-thread-safe data structures sounds like enough.

spurserh
+1  A: 

I'm going to go out on a limb here and assume you want to copy the camera image in a serial fashion, then operate on the copied data (the IplImage) in a multi-threaded way.

To safely do this, as the unknown guy pointed out, you have to lock the memory (or variable(s)) you're potentially accessing with your threads. A very short example of how to do this with a Windows CRITICAL_SECTION is as follows:

CRITICAL_SECTION cs;

/* Initialize the critical section -- This must be done before locking */
InitializeCriticalSection(&cs);

...

/* Release system object when all finished -- 
usually at the end of the cleanup code */
DeleteCriticalSection(&cs);

Now when you're accessing the camera (or any un-sharable resource for that matter) you simply surround the thing you're accessing with the following two lines:

EnterCriticalSection(&cs);

/* Operate on your shared data */

LeaveCriticalSection(&cs);

Surrounding your code (e.g. IplImage* frame = cvQueryFrame(xyz);) with these two lines should fix your collisions.. but it sounds like your code could do with a little more organization..

Rooke