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_single_producer.h"
17 #define N_ITERATIONS 10000000
21 #define QUEUE_SIZE 1000
24 void TestLockFreeQueue()
26 ArrayLockFreeQueueSingleProducer<int, QUEUE_SIZE> theQueue;
27 GTimeVal iniTimestamp;
28 GTimeVal endTimestamp;
30 std::cout << "=== Start of testing lock-free queue ===" << std::endl;
31 g_get_current_time(&iniTimestamp);
32 #pragma omp parallel shared(theQueue) num_threads (2)
34 if (omp_get_thread_num() == 0)
36 //std::cout << "=== Testing Non blocking queue with " << omp_get_num_threads() << " threads ===" << std::endl;
38 if (!omp_get_nested())
40 std::cerr << "WARNING: Nested parallel regions not supported. Working threads might have unexpected behaviour" << std::endl;
41 std::cerr << "Are you running with \"OMP_NESTED=TRUE\"??" << std::endl;
45 #pragma omp sections //nowait
49 // producer section. only 1 thread
50 //#pragma omp parallel shared(theQueue) num_threads (1)
52 //if (omp_get_thread_num() == 0)
54 // std::cout << "\t Producers: " << omp_get_num_threads() << std::endl;
57 for (i = 0 ; i < N_ITERATIONS ; i++)
59 while(!theQueue.push(i))
71 #pragma omp parallel shared(theQueue) num_threads (N_CONSUMERS)
73 //if (omp_get_thread_num() == 0)
75 // std::cout << "\t Consumers: " << omp_get_num_threads() << std::endl;
80 #pragma omp for schedule(static) private(i, result) nowait
81 for (i = 0 ; i < N_ITERATIONS ; i++)
83 while (!theQueue.pop(result))
90 // if there are several consumers this test will fail
93 std::cout << "FAILED i=" << i << " result=" << result << std::endl;
101 } // #pragma omp parallel
103 g_get_current_time(&endTimestamp);
105 // calculate elapsed time
106 GTimeVal elapsedTime;
107 if (endTimestamp.tv_usec >= iniTimestamp.tv_usec)
109 elapsedTime.tv_sec = endTimestamp.tv_sec - iniTimestamp.tv_sec;
110 elapsedTime.tv_usec = endTimestamp.tv_usec - iniTimestamp.tv_usec;
114 elapsedTime.tv_sec = endTimestamp.tv_sec - iniTimestamp.tv_sec - 1;
115 elapsedTime.tv_usec = G_USEC_PER_SEC + endTimestamp.tv_usec - iniTimestamp.tv_usec;
118 std::cout << "Elapsed: " << elapsedTime.tv_sec << "." << elapsedTime.tv_usec << std::endl;
119 std::cout << "=== End of testing lock-free queue ===" << std::endl;
122 int main(int /*argc*/, char** /*argv*/)
126 std::cout << "Done!!!" << std::endl;