Twitch SDK (Internal)
concurrentqueue.h
Go to the documentation of this file.
1 /********************************************************************************************
2 * Twitch Broadcasting SDK
3 *
4 * This software is supplied under the terms of a license agreement with Twitch Interactive, Inc. and
5 * may not be copied or used except in accordance with the terms of that agreement
6 * Copyright (c) 2012-2016 Twitch Interactive, Inc.
7 *********************************************************************************************/
8 
9 #pragma once
10 
11 #include "twitchsdk/core/mutex.h"
12 #include <queue>
13 
14 namespace ttv
15 {
16  template <typename TYPE> class ConcurrentQueue;
17 }
18 
22 template <typename TYPE>
24 {
25 public:
27  {
29  assert(TTV_SUCCEEDED(ec) && mMutex != nullptr);
30  UNUSED(ec);
31  }
32 
33 public:
34  void clear()
35  {
36  AutoMutex lock(mMutex);
37  while (!mQueue.empty())
38  {
39  mQueue.pop();
40  }
41  }
42 
43  bool empty() const
44  {
45  AutoMutex lock(mMutex);
46  return mQueue.empty();
47  }
48 
52  void push(const TYPE& item)
53  {
54  AutoMutex lock(mMutex);
55  mQueue.emplace(item);
56  }
57 
61  void push(TYPE&& item)
62  {
63  AutoMutex lock(mMutex);
64  mQueue.emplace(std::forward<TYPE>(item));
65  }
66 
76  bool try_pop(TYPE& result)
77  {
78  // NOTE: Reset the value before entering the lock to avoid resources potentially being
79  // cleaned up while under the lock during assignment
80  result = {};
81 
82  bool ret = false;
83 
84  AutoMutex lock(mMutex);
85  if (!mQueue.empty())
86  {
87  result = std::move(mQueue.front());
88  mQueue.pop();
89  ret = true;
90  }
91 
92  return ret;
93  }
94 
98  size_t unsafe_size() const
99  {
100  return mQueue.size();
101  }
102 
103 private:
104  std::queue<TYPE> mQueue;
105  std::shared_ptr<IMutex> mMutex;
106 };
void clear()
Definition: concurrentqueue.h:34
ConcurrentQueue()
Definition: concurrentqueue.h:26
bool try_pop(TYPE &result)
Definition: concurrentqueue.h:76
JSON (JavaScript Object Notation).
Definition: adsapi.h:16
#define TTV_SUCCEEDED(ec)
Definition: errortypes.h:230
#define assert(expr)
Definition: assertion.h:47
size_t unsafe_size() const
Definition: concurrentqueue.h:98
TTV_ErrorCode CreateMutex(std::shared_ptr< IMutex > &result)
uint32_t TTV_ErrorCode
Definition: errortypes.h:30
Definition: concurrentqueue.h:16
std::shared_ptr< IMutex > mMutex
Definition: concurrentqueue.h:105
Definition: mutex.h:119
std::queue< TYPE > mQueue
Definition: concurrentqueue.h:104
#define UNUSED(x)
Definition: coretypes.h:15
bool empty() const
Definition: concurrentqueue.h:43
void push(TYPE &&item)
Definition: concurrentqueue.h:61
void push(const TYPE &item)
Definition: concurrentqueue.h:52