开发者

How to access a global variable from a worker thread

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 t开发者_如何学编程ried 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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜