0

I have three separate threads that get the same object. Each of the threads has different values.

class ClassA{
    int counter_a = 0;
    int counter_b = 0;
    int counter_c = 0;
    
    void startCounterA() {
        this->counter_a++;
    }
    void startCounterB() {
        this->counter_b++;
    }
    void startCounterC() {
        this->counter_c++;
    }
};
        ClassA a;

        std::thread pt(&ClassA::startCounterA, a);
        pt.join();

        std::thread ct(&ClassA::startCounterB, a);
        ct.join();
        std::thread mt(&ClassA::startCounterC, a);
        
        mt.join();

When the threads finish running all the values is zero. why? how can I solve it?

KOKO
  • 1
  • It is because nothing that these execution threads do is correctly synchronized. Thread synchronization is a fairly complicated topic involving objects like mutexes and condition variables. It can't be fully explained in one or two sentences on Stackoverflow, and is best to be explained by a good C++ textbook on this topic. – Sam Varshavchik Nov 24 '21 at 01:47
  • @SamVarshavchik Those threads are executed sequentially, there is never two threads running at the same time in the example shown. They are synchronized by `join()`. Each thread is also incrementing a different variable. – François Andrieux Nov 24 '21 at 02:06
  • `join()` only synchronizes the completion of one execution thread with the return from `join()`. Nothing more, nothing less. – Sam Varshavchik Nov 24 '21 at 02:30
  • @SamVarshavchik Anything the joined thread does is sequenced before anything that the joining thread would do after the `join()`. Since each thread is sequenced after the previous' `join()` there is no race condition here. For the purposes of race conditions, this code is basically single threaded. – François Andrieux Nov 24 '21 at 02:58

0 Answers0