c 2b 2b mutex lock

Solutions on MaxInterview for c 2b 2b mutex lock by the best coders in the world

showing results for - "c 2b 2b mutex lock"
Ariana
14 Apr 2016
1// mutex::lock/unlock
2#include <iostream>       // std::cout
3#include <thread>         // std::thread
4#include <mutex>          // std::mutex
5
6std::mutex mtx;           // mutex for critical section
7
8void print_thread_id (int id) {
9  // critical section (exclusive access to std::cout signaled by locking mtx):
10  mtx.lock();
11  std::cout << "thread #" << id << '\n';
12  mtx.unlock();
13}
14
15int main ()
16{
17  std::thread threads[10];
18  // spawn 10 threads:
19  for (int i=0; i<10; ++i)
20    threads[i] = std::thread(print_thread_id,i+1);
21
22  for (auto& th : threads) th.join();
23
24  return 0;
25}