aboutsummaryrefslogtreecommitdiff
path: root/store/works/life/operating-system-experiment/SemaphoreAvoidDataRaceDemo.cpp
blob: 0068082903d08889e614e03209d94a22c0850218 (plain)
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
29
30
31
32
33
34
35
36
#include "Semaphore.h"
#include "Thread.h"

#include <iostream>

int main() {
  unsigned data = 0;

  cru::Semaphore semaphore;

  cru::Thread t1([&data, &semaphore] {
    for (int i = 0; i < 100000; i++) {
      semaphore.P();
      data += 10;
      semaphore.V();
    }
  });

  cru::Thread t2([&data, &semaphore] {
    for (int i = 0; i < 100000; i++) {
      semaphore.P();
      data += 10;
      semaphore.V();
    }
  });

  std::cout << "Created thread: " << t1.GetNativeID() << '\n';
  std::cout << "Created thread: " << t2.GetNativeID() << '\n';

  t1.Join();
  t2.Join();
  std::cout << "Answer is " << data << ", which is "
            << (data == 2000000 ? "correct" : "false") << '\n';

  return 0;
}