forest-net
an overlay networks for large-scale virtual worlds
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator
foo.cpp
1 #include <iostream>
2 #include <thread>
3 #include <mutex>
4 #include <chrono>
5 #include <atomic>
6 
7 using std::mutex;
8 using std::unique_lock;
9 using namespace std::chrono;
10 using std::cout;
11 using std::endl;
12 
13 mutex mtx;
14 
15 std::atomic<uint64_t> count;
16 
17 int i = 0; // shared value by producers and consumers
18 
19 void t1() {
20  while (i < 1000)
21  std::this_thread::sleep_for(milliseconds(1));
22  count +=5;
23 }
24 
25 
26 void t2() {
27  high_resolution_clock::time_point t1 = high_resolution_clock::now();
28  while (i < 10000 ) {
29  count++;
30  unique_lock<mutex> lck(mtx);
31  i++;
32  lck.unlock();
33  }
34  high_resolution_clock::time_point t2 = high_resolution_clock::now();
35  nanoseconds dtn(t2-t1);
36  cout << dtn.count() << endl;
37 }
38 
39 int main () {
40  std::thread first(t1);
41  std::thread second(t2);
42 
43  first.join();
44  second.join();
45 
46  cout << count << endl;
47 
48  return 0;
49 }