#include #include #include #include #include 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 _(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); }