Merge branch 'master' of /scratch/mine/libcds
[libcds.git] / test / stress / misc / rwqueue_driver.cpp
1 #include <cds/container/rwqueue.h>
2 #include <cstdlib>
3 #include <ctime>
4 #include <iostream>
5 #include <string>
6
7 using namespace std;
8
9 cds::container::RWQueue<int> queue;
10
11 void InitQueue() {
12   for (int i = 0; i < 2000000; i++) {
13     queue.enqueue(rand() % 100);
14   }
15 }
16
17 void ProducerThread() {
18   for (int i = 0; i < 1000000; i++) {
19     for (int j = 0; j < 50; j++) {
20       queue.enqueue(rand() % 100);
21     }
22   }
23 }
24
25 void ProducerConsumerThread() {
26   unsigned long long sum = 0;
27   int element;
28   for (int i = 0; i < 1000000; i++) {
29     for (int j = 0; j < 50; j++) {
30       if (!queue.empty() && queue.dequeue(element)) {
31         sum += element;
32       }
33       if (j % 2 == 0) {
34         queue.enqueue(rand() % 100);
35       }
36     }
37   }
38 }
39
40 void ConsumerThread() {
41   int element;
42   unsigned long long sum = 0;
43   int yield_times = 3;
44   while (yield_times > 0) {
45     while (queue.dequeue(element)) {
46       sum += element;
47       yield_times = 3;
48     }
49     std::this_thread::yield();
50     yield_times--;
51   }
52 }
53
54 int main() {
55   srand(time(NULL));
56   const int kThreads = 6;
57   // Initialize the queue with some elements.
58   InitQueue();
59   cout << "Starting " << kThreads << " threads for RWQueue...\n";
60
61   struct timespec start, finish;
62   double elapsed = 0.0;
63   clock_gettime(CLOCK_MONOTONIC, &start);
64
65   std::thread threads[kThreads];
66   // Producer thread
67   threads[0] = std::thread(ProducerThread);
68   // ProducerConsumer threads
69   for (int i = 1; i < kThreads; i++) {
70     threads[i] = std::thread(ProducerConsumerThread);
71   }
72
73   for (int i = 0; i < kThreads; i++) {
74     threads[i].join();
75   }
76
77   clock_gettime(CLOCK_MONOTONIC, &finish);
78   elapsed = (finish.tv_sec - start.tv_sec);
79   elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
80   cout << "All threads finished.\n";
81   cout << "Time: " << elapsed << " seconds\n";
82   return 0;
83 }