troubleshooting Question

C++ using a critical section

Avatar of deleyd
deleydFlag for United States of America asked on
10 Comments1 Solution1686 ViewsLast Modified:
I see a lovely Critical Section wrapper at

Now I just need some example code of how to use it properly. This will be for unmanaged C++ code.

Say I have a class, MyClass, and that class has a private variable, myVariable (an integer, or a long if that's better, or unsigned integer, whatever works best, if it makes a difference), and I want to be able to safely write and read that variable from multiple threads, so I need to make sure one thread isn't writing while another is reading.

So I have a class CriticalSection.h defined (from the link above).

And now I have MyClass.h:
#pragma once
class MyClass

  int myVariable;
  void ThreadSafeWrite(int i);
  int  ThreadSafeRead();

  SetMyVariable(int i) {
  int GetMyVariable(void) {
    return ThreadSafeRead();
Now I'm not sure, do I have MyClass inherit CriticalSection? And how would I implement ThreadSafeRead and ThreadSafeWrite?
Join our community to see this answer!
Unlock 1 Answer and 10 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 10 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros