Will this make the object thread-safe?

Posted by sharptooth on Stack Overflow See other posts from Stack Overflow or by sharptooth
Published on 2010-03-12T08:39:07Z Indexed on 2010/03/12 8:47 UTC
Read the original article Hit count: 203

I have a native Visual C++ COM object and I need to make it completely thread-safe to be able to legally mark it as "free-threaded" in th system registry. Specifically I need to make sure that no more than one thread ever accesses any member variable of the object simultaneously.

The catch is I'm almost sure that no sane consumer of my COM object will ever try to simultaneously use the object from more than one thread. So I want the solution as simple as possible as long as it meets the requirement above.

Here's what I came up with. I add a mutex or critical section as a member variable of the object. Every COM-exposed method will acquire the mutex/section at the beginning and release before returning control.

I understand that this solution doesn't provide fine-grained access and this might slow execution down, but since I suppose simultaneous access will not really occur I don't care of this.

Will this solution suffice? Is there a simpler solution?

© Stack Overflow or respective owner

Related posts about language-agnostic

Related posts about multithreading