views:

40

answers:

3

I have a vc++ 2005 dialog based application, where I use a worker thread to do some background processing.

The worker thread is implemented as a global function in the dialog class

I am able to access the variables of the dialog class inside the worker thread but I am not able to get some of their their values correctly inside the worker thread.

For example, I have initialized a COM object (using CoInitilize) in the dialog class, but I am not able to access its latest value. I tried declaring them globally but still I couldn't get their values inside the thread.

Please tell me how can I access COM objects inside worker threads

Thanks.

A: 

You need to have memory barriers when accessing variables from different threads. (And you may also need to protect variables against concurrent access.)

The easiest way to achieve (both of) this is to use whatever kind of mutex your platform provides. For example, the Win32 API has Critical Sections for this.

sbi
A: 

Use the keyword "volatile". It tells the compiler that the variable is defined somewhere in 'volatile' memory and that it must not try to optimize this variable by using registers.

See http://msdn.microsoft.com/en-us/library/12a04hfd%28VS.80%29.aspx for an explanation on MSDN.

Patrick
+1  A: 

CoInitialize function must be called in every thread that you starts, if you want to use any COM object inside it. Check MSDN documentation of this function. Please also remember to deinitialize COM before exiting from thread.

Zuljin