0

FileA.h

struct MyCounter{
int count;
};

class Counter {
public:
    MyCounter mycounter;
    void CreateThread(); // starts a thread
    void DestroyThread();
    void PrintCount(); // this function is called while the thread is running, 
                       // reads the value of "count" and prints and is protected by a mutex while reading
};

class Singleton {
public:
    Singleton& getInstance();
    Counter counter;
};

FileB.cpp

// create static Singleton object say, S = Singleton->GetInstance()

void func1() {
    S.counter.mycounter.count++; // My question is here: Is it okay to increment this counter here without using a mutex?
}

void func2() {
    S.counter.CreateThread(); // Create a thread here
}

What is the best way to increment the "count" variable which is thread safe?

halfer
  • 19,824
  • 17
  • 99
  • 186
RRR
  • 339
  • 1
  • 6
  • 15
  • 2
    Could you just make it `atomic`? – Tas Feb 05 '20 at 21:52
  • It's strange for a singleton's `getInstance` to return by value. You probably meant to return `Singleton&`. – François Andrieux Feb 05 '20 at 21:54
  • I could use atomic if it was a primitive but what if it is struct? Let me edit my question. Thanks. – RRR Feb 05 '20 at 21:56
  • The rule is you need synchronization if you have more than one thread and at least one of them is a writer and the threads are accessing the same object. – NathanOliver Feb 05 '20 at 21:58
  • 1
    If it's not primitive take care that you are not trying to protect at the wrong level. Inside `Counter` `count` could still be `atomic` and you don't need to protect `Counter`.If you have to, for example, "simultaneously" change two variables, consider using a `std::mutex`. – user4581301 Feb 05 '20 at 22:00
  • you mean something like this: struct Counter { atomic count – RRR Feb 05 '20 at 22:03
  • Yes. Always try to keep the protection as narrow as possible, but when you do have a complicated case take care that you don't narrow the protection too much. [Famous example of too narrow](https://stackoverflow.com/questions/1386275/why-is-java-vector-and-stack-class-considered-obsolete-or-deprecated). – user4581301 Feb 05 '20 at 22:17
  • Can someone please point me to a good example of using a std::atomic? Thanks. – RRR Feb 06 '20 at 02:52
  • I'm not sure what answer you want beyond using `std::atomic` if that does what you need and a mutex if not. – David Schwartz Mar 06 '20 at 09:44

0 Answers0