aboutsummaryrefslogtreecommitdiff
path: root/works/life/operating-system-experiment/MutexAvoidDataRaceDemo.cpp
blob: 81a7aa1df3464a917ca369a233ad7110fb9c9734 (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
37
38
39
40
41
42
#include "Mutex.h"
#include "Thread.h"

#include <iostream>

int main() {

  unsigned data = 0;
  cru::Mutex mutex;
  mutex.Lock();

  cru::Thread t1([&data, &mutex] {
    for (int i = 0; i < 100000; i++) {
      mutex.Lock();
      data += 10;
      //std::cout << "Data is now: " << data << '\n';
      mutex.Unlock();
    }
  });

  cru::Thread t2([&data, &mutex] {
    for (int i = 0; i < 100000; i++) {
      mutex.Lock();
      data += 10;
      //std::cout << "Data is now: " << data << '\n';
      mutex.Unlock();
    }
  });

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

  mutex.Unlock();

  t1.Join();
  t2.Join();

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

  return 0;
}