diff --git a/cpp_impl/src/TSQueue.hpp b/cpp_impl/src/TSQueue.hpp index 1afae60..0a5e616 100644 --- a/cpp_impl/src/TSQueue.hpp +++ b/cpp_impl/src/TSQueue.hpp @@ -9,6 +9,8 @@ class TSQueue { public: + typedef std::unique_ptr TopType; + TSQueue(unsigned int elemSize, unsigned int capacity = UDPC_TSQUEUE_DEFAULT_CAPACITY); ~TSQueue(); @@ -21,7 +23,7 @@ class TSQueue { TSQueue &operator=(TSQueue &&other) = delete; bool push(void *data); - std::unique_ptr top(); + TopType top(); bool pop(); void clear(); void changeCapacity(unsigned int newCapacity); diff --git a/cpp_impl/src/test/TestTSQueue.cpp b/cpp_impl/src/test/TestTSQueue.cpp index 698a0da..f1adeea 100644 --- a/cpp_impl/src/test/TestTSQueue.cpp +++ b/cpp_impl/src/test/TestTSQueue.cpp @@ -1,5 +1,8 @@ #include +#include +#include + #include "TSQueue.hpp" TEST(TSQueue, Usage) @@ -107,3 +110,44 @@ TEST(TSQueue, Usage) EXPECT_FALSE(q.pop()); EXPECT_EQ(0, q.size()); } + +TEST(TSQueue, Concurrent) +{ + TSQueue q(sizeof(int), 4); + + auto a0 = std::async(std::launch::async, [&q] () {int i = 0; return q.push(&i); }); + auto a1 = std::async(std::launch::async, [&q] () {int i = 1; return q.push(&i); }); + auto a2 = std::async(std::launch::async, [&q] () {int i = 2; return q.push(&i); }); + auto a3 = std::async(std::launch::async, [&q] () {int i = 3; return q.push(&i); }); + auto a4 = std::async(std::launch::async, [&q] () {int i = 4; return q.push(&i); }); + + bool results[] = { + a0.get(), + a1.get(), + a2.get(), + a3.get(), + a4.get() + }; + + int insertCount = 0; + for(int i = 0; i < 5; ++i) { + if(results[i]) { + ++insertCount; + } + } + + EXPECT_EQ(insertCount, 4); + EXPECT_EQ(q.size(), 4); + + TSQueue::TopType top; + for(int i = 0; i < 4; ++i) { + top = q.top(); + EXPECT_TRUE(q.pop()); + EXPECT_EQ(q.size(), 3 - i); + printf("%d ", *((int*)top.get())); + } + printf("\n"); + + EXPECT_FALSE(q.pop()); + EXPECT_EQ(q.size(), 0); +}