C ++ использование (общей) переменной между двумя потоками - PullRequest
0 голосов
/ 06 февраля 2020

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
}

Каков наилучший способ увеличить переменную count, которая является поточно-ориентированной?

...