I'm trying to understand C++ Multithreading and synchronize between many threads. Thus I created 2 threads the first one increments a value and the second one decrements it. what I can't understand why the resulted value after the execution is different than the first one, since I added and subtracted from the same value.
static unsigned int counter = 100; static bool alive = true; static Lock lock; std::mutex mutex; void add() { while (alive) { mutex.lock(); counter += 10; std::cout << "Counter Add = " << counter << std::endl; mutex.unlock(); } } void sub() { while (alive) { mutex.lock(); counter -= 10; std::cout << "Counter Sub = " << counter<< std::endl; mutex.unlock(); } } int main() { std::cout << "critical section value at the start " << counter << std::endl; std::thread tAdd(add); std::thread tSub(sub); Sleep(1000); alive = false; tAdd.join(); tSub.join(); std::cout << "critical section value at the end " << counter << std::endl; return 0; } Output
critical section value at the start 100
critical section value at the end 220
So what I need is how to keep my value as it's, I mean counter equal to 100 using those two threads.
counterwill always equal 100. Well really: it's just not clear what you want to achieve.