Critical Section

The critical section is a section of code within a process that requires access to shared resources and has to be executed as an Atomic Operation. It must not be executed by more than one thread at a time to prevent data corruption.

Example

#include <iostream>
#include <thread>
#include <mutex>
 
std::mutex mtx; // Mutex for critical section
 
void printNumbers() {
    mtx.lock(); // Entering critical section
    for(int i = 0; i < 5; ++i) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    mtx.unlock(); // Exiting critical section
}
 
int main() {
    std::thread t1(printNumbers);
    std::thread t2(printNumbers);
    t1.join();
    t2.join();
    return 0;
}