1 // ============================================================================
2 /// @file test_lock_free_q.cpp
3 /// @brief Benchmark lock free queue
4 // ============================================================================
8 #include <glib.h> // GTimeVal + g_get_current_time
9 #include <omp.h> // parallel processing support in gcc
10 #include "array_lock_free_queue.h"
21 #define N_ITERATIONS 10000000
25 #define QUEUE_SIZE 1024
28 void TestLockFreeQueue()
30 ArrayLockFreeQueue<int, QUEUE_SIZE> theQueue;
31 GTimeVal iniTimestamp;
32 GTimeVal endTimestamp;
34 std::cout << "=== Start of testing lock-free queue ===" << std::endl;
35 g_get_current_time(&iniTimestamp);
36 #pragma omp parallel shared(theQueue) num_threads (2)
38 if (omp_get_thread_num() == 0)
40 //std::cout << "=== Testing Non blocking queue with " << omp_get_num_threads() << " threads ===" << std::endl;
42 if (!omp_get_nested())
44 std::cerr << "WARNING: Nested parallel regions not supported. Working threads might have unexpected behaviour" << std::endl;
45 std::cerr << "Are you running with \"OMP_NESTED=TRUE\"??" << std::endl;
49 #pragma omp sections //nowait
54 #pragma omp parallel shared(theQueue) num_threads (N_PRODUCERS)
56 //if (omp_get_thread_num() == 0)
58 // std::cout << "\t Producers: " << omp_get_num_threads() << std::endl;
61 #pragma omp for schedule(static) private(i) nowait
62 for (i = 0 ; i < N_ITERATIONS ; i++)
64 while(!theQueue.push(i))
75 #pragma omp parallel shared(theQueue) num_threads (N_CONSUMERS)
77 //if (omp_get_thread_num() == 0)
79 // std::cout << "\t Consumers: " << omp_get_num_threads() << std::endl;
84 #pragma omp for schedule(static) private(i, result) nowait
85 for (i = 0 ; i < N_ITERATIONS ; i++)
87 while (!theQueue.pop(result))
92 #if (N_CONSUMERS == 1 && N_PRODUCERS == 1)
95 std::cout << "FAILED i=" << i << " result=" << result << std::endl;
103 } // #pragma omp parallel
105 g_get_current_time(&endTimestamp);
107 // calculate elapsed time
108 GTimeVal elapsedTime;
109 if (endTimestamp.tv_usec >= iniTimestamp.tv_usec)
111 elapsedTime.tv_sec = endTimestamp.tv_sec - iniTimestamp.tv_sec;
112 elapsedTime.tv_usec = endTimestamp.tv_usec - iniTimestamp.tv_usec;
116 elapsedTime.tv_sec = endTimestamp.tv_sec - iniTimestamp.tv_sec - 1;
117 elapsedTime.tv_usec = G_USEC_PER_SEC + endTimestamp.tv_usec - iniTimestamp.tv_usec;
120 std::cout << "Elapsed: " << elapsedTime.tv_sec << "." << elapsedTime.tv_usec << std::endl;
121 std::cout << "=== End of testing lock-free queue ===" << std::endl;
124 int main(int /*argc*/, char** /*argv*/)
128 std::cout << "Done!!!" << std::endl;