Sobes.tech
Junior — Senior

Simultaneous increase of a shared variable by two threads with delay

livecode

Task condition

A global variable counter1 is declared in the program. Two threads are created, each of which waits for two seconds before starting work, then performs 100,000 increments of counter1. After both threads finish, the value of counter1 is displayed on the screen.

static int counter1;

void run()
{
    auto threadFunc = []()
    {
        using namespace std::chrono_literals;
        std::this_thread::sleep_for(2000ms);
        for (int i = 0; i < 100000; i++)
        {
            ++counter1;
        }
    };

    std::thread th(threadFunc), th2(threadFunc);
    th.join();
    th2.join();
    std::cout << counter1 << std::endl;
}