Add new methods to tizen_base::SharedQueue 69/286669/2
authorHwankyu Jhun <h.jhun@samsung.com>
Wed, 11 Jan 2023 11:21:41 +0000 (11:21 +0000)
committerJunghoon Park <jh9216.park@samsung.com>
Wed, 11 Jan 2023 23:14:52 +0000 (23:14 +0000)
Adds:
 - TryAndPop()
 - WaitAndPopFor()

Change-Id: I4bdbdcd146340708d9409ad381585e8ff43a0cd3
Signed-off-by: Hwankyu Jhun <h.jhun@samsung.com>
tests/tizen-shared-queue_unittests/test_shared_queue.cc
tizen-shared-queue/shared-queue.hpp

index a20c398..d41ca40 100644 (file)
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <chrono>
 #include <iostream>
 #include <thread>
 
@@ -52,6 +53,35 @@ TEST(SharedQueueTest, PushAndWaitAndPop) {
   EXPECT_TRUE(job.Done());
 }
 
+TEST(SharedQueueTest, TryAndPop) {
+  tizen_base::SharedQueue<Job> queue;
+  Job job;
+  EXPECT_FALSE(queue.TryAndPop(job));
+  queue.Push(Job());
+  EXPECT_TRUE(queue.TryAndPop(job));
+}
+
+TEST(SharedQueueTest, WaitAndPopFor) {
+  tizen_base::SharedQueue<Job> queue;
+  Job job;
+  std::chrono::steady_clock::time_point begin =
+      std::chrono::steady_clock::now();
+  EXPECT_FALSE(queue.WaitAndPopFor(job, 110));
+  std::chrono::steady_clock::time_point end =
+      std::chrono::steady_clock::now();
+  auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(
+      end - begin).count();
+  EXPECT_TRUE(elapsed_time > 100);
+
+  queue.Push(Job());
+  begin = std::chrono::steady_clock::now();
+  EXPECT_TRUE(queue.WaitAndPopFor(job, 100));
+  end = std::chrono::steady_clock::now();
+  elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(
+      end - begin).count();
+  EXPECT_TRUE(elapsed_time < 100);
+}
+
 TEST(SharedQueueTest, IsEmpty) {
   tizen_base::SharedQueue<Job> queue;
   EXPECT_TRUE(queue.IsEmpty());
index 648d31d..f73552d 100644 (file)
@@ -38,6 +38,16 @@ class SharedQueue {
     cond_var_.notify_one();
   }
 
+  bool TryAndPop(T& item) {
+    std::lock_guard<std::mutex> lock(mutex_);
+    if (queue_.empty())
+      return false;
+
+    item = queue_.front();
+    queue_.pop();
+    return true;
+  }
+
   T WaitAndPop() {
     std::unique_lock<std::mutex> lock(mutex_);
     while (queue_.empty())
@@ -48,6 +58,23 @@ class SharedQueue {
     return item;
   }
 
+  bool WaitAndPopFor(T& item, int timeout) {
+    std::unique_lock<std::mutex> lock(mutex_);
+    if (!queue_.empty()) {
+      item = queue_.front();
+      queue_.pop();
+      return true;
+    }
+
+    std::chrono::milliseconds duration(timeout);
+    if (cond_var_.wait_for(lock, duration) == std::cv_status::timeout)
+      return false;
+
+    item = queue_.front();
+    queue_.pop();
+    return true;
+  }
+
   bool IsEmpty() const {
     std::lock_guard<std::mutex> lock(mutex_);
     return queue_.empty();