File: test10.cpp

package info (click to toggle)
box64 0.3.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 22,576 kB
  • sloc: ansic: 333,323; python: 2,695; asm: 1,014; makefile: 266; sh: 83; cpp: 45
file content (28 lines) | stat: -rw-r--r-- 764 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// using atomic as a lock
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector
#include <sstream>        // std::stringstream

std::atomic<bool> lock_stream[10];
std::stringstream stream;

void append_number(int x) {
  while (lock_stream[x].load()) {}
  stream << "thread #" << x << '\n';
  stream.flush();
  if (x != 9) lock_stream[x + 1].store(false);
}

int main ()
{
  std::vector<std::thread> threads;
  for (int i = 0; i < 10; ++i) lock_stream[i].store(true);
  for (int i=0; i<10; ++i) threads.push_back(std::thread(append_number,i));
  lock_stream[0].store(false);
  for (auto& th : threads) th.join();

  std::cout << stream.str();
  return 0;
}