trainings/C_secure_coding/SecC++/examples/data_race.cpp

30 lines
569 B
C++

#include <thread>
#include <iostream>
#include <cassert>
#include <chrono>
#include <mutex>
int counter = 65535;
std::mutex mtx = {};
void worker(int delta) {
for (auto i = 0U; i < 100; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
// Zła praktyka! Zawsze rób to RAII!
// mtx.lock();
{ // Critical section
std::lock_guard<std::mutex> _(mtx);
counter += delta;
}
// mtx.unlock();
}
}
int main() {
auto t1 = std::thread(worker, 1);
auto t2 = std::thread(worker, -1);
t2.join();
t1.join();
assert(counter == 65535);
}