Skip to content
Snippets Groups Projects
Select Git revision
  • 7c15bf3d194b92af5f6891187359286adc9e961f
  • master default protected
2 results

atomic.cpp

Blame
  • mutex.cpp 625 B
    #include <array>
    #include <thread>
    #include <iostream>
    
    int main() {
        constexpr auto n_threads = 10u;
        std::array<std::thread, n_threads> threads;
        std::mutex cout_mutex;
    
        const auto hello = [&cout_mutex](int i) {
            // Uncommenting this line will randomly interleave all the threads' outputs.
            std::lock_guard<std::mutex> cout_lock(cout_mutex);
            std::cout << "Hello from thread " << i << '\n';
        };
    
        for (auto i = 0u; i < n_threads; ++i) {
            threads[i] = std::thread(hello, i);
        }
    
        for (auto i = 0u; i < n_threads; ++i) {
            threads[i].join();
        }
    
        return 0;
    }