/*
Thread synchronization is a mechanism that ensures that two or more concurrent 
threads do not simultaneously execute certain program segments, called "critical
sections". This can be important to prevent race conditions, where the outcome of 
the program depends on the order in which the threads are scheduled.

One way to achieve thread synchronization in C++ is by using a "mutex" (short for
"mutual exclusion"). A mutex is a synchronization object that allows only one 
thread to execute a critical section at a time.
*/

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int shared_variable = 0;

void increment() {
    for (int i = 0; i < 10; i++) {
        mtx.lock();
        shared_variable++;
        std::cout << "Thread " << std::this_thread::get_id() << " increments shared variable to " << shared_variable << std::endl;
        mtx.unlock();
    }
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);

    t1.join();
    t2.join();

    std::cout << "Final value of shared variable: " << shared_variable << std::endl;
    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: