-#include <cds/container/rwqueue.h>
-#include <cstdlib>
-#include <ctime>
-#include <iostream>
-#include <string>
-
-using namespace std;
-
-cds::container::RWQueue<int> queue;
-
-void InitQueue() {
- for (int i = 0; i < 2000000; i++) {
- queue.enqueue(rand() % 100);
- }
-}
-
-void ProducerThread() {
- for (int i = 0; i < 1000000; i++) {
- for (int j = 0; j < 50; j++) {
- queue.enqueue(rand() % 100);
- }
- }
-}
-
-void ProducerConsumerThread() {
- unsigned long long sum = 0;
- int element;
- for (int i = 0; i < 1000000; i++) {
- for (int j = 0; j < 50; j++) {
- if (!queue.empty() && queue.dequeue(element)) {
- sum += element;
- }
- if (j % 2 == 0) {
- queue.enqueue(rand() % 100);
- }
- }
- }
-}
-
-void ConsumerThread() {
- int element;
- unsigned long long sum = 0;
- int yield_times = 3;
- while (yield_times > 0) {
- while (queue.dequeue(element)) {
- sum += element;
- yield_times = 3;
- }
- std::this_thread::yield();
- yield_times--;
- }
-}
-
-int main() {
- srand(time(NULL));
- const int kThreads = 6;
- // Initialize the queue with some elements.
- InitQueue();
- cout << "Starting " << kThreads << " threads for RWQueue...\n";
-
- struct timespec start, finish;
- double elapsed = 0.0;
- clock_gettime(CLOCK_MONOTONIC, &start);
-
- std::thread threads[kThreads];
- // Producer thread
- threads[0] = std::thread(ProducerThread);
- // ProducerConsumer threads
- for (int i = 1; i < kThreads; i++) {
- threads[i] = std::thread(ProducerConsumerThread);
- }
-
- for (int i = 0; i < kThreads; i++) {
- threads[i].join();
- }
-
- clock_gettime(CLOCK_MONOTONIC, &finish);
- elapsed = (finish.tv_sec - start.tv_sec);
- elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
- cout << "All threads finished.\n";
- cout << "Time: " << elapsed << " seconds\n";
- return 0;
-}