| 27 | |
| 28 | template <typename T> |
| 29 | class Queue |
| 30 | { |
| 31 | public: |
| 32 | Queue() : data(new Data()) {} |
| 33 | |
| 34 | // TODO(bmahler): Take a T&& here instead. |
| 35 | void put(const T& t) |
| 36 | { |
| 37 | // NOTE: We need to grab the promise 'date->promises.front()' but |
| 38 | // set it outside of the critical section because setting it might |
| 39 | // trigger callbacks that try to reacquire the lock. |
| 40 | Owned<Promise<T>> promise; |
| 41 | |
| 42 | synchronized (data->lock) { |
| 43 | if (data->promises.empty()) { |
| 44 | data->elements.push(t); |
| 45 | } else { |
| 46 | promise = data->promises.front(); |
| 47 | data->promises.pop_front(); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | if (promise.get() != nullptr) { |
| 52 | promise->set(t); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | Future<T> get() |
| 57 | { |
| 58 | Future<T> future; |
| 59 | |
| 60 | synchronized (data->lock) { |
| 61 | if (data->elements.empty()) { |
| 62 | data->promises.emplace_back(new Promise<T>()); |
| 63 | future = data->promises.back()->future(); |
| 64 | } else { |
| 65 | T t = std::move(data->elements.front()); |
| 66 | data->elements.pop(); |
| 67 | return Future<T>(std::move(t)); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // If there were no items available, we set up a discard |
| 72 | // handler. This is done here to minimize the amount of |
| 73 | // work done within the critical section above. |
| 74 | auto weak_data = std::weak_ptr<Data>(data); |
| 75 | |
| 76 | future.onDiscard([weak_data, future]() { |
| 77 | auto data = weak_data.lock(); |
| 78 | if (!data) { |
| 79 | return; |
| 80 | } |
| 81 | |
| 82 | synchronized (data->lock) { |
| 83 | for (auto it = data->promises.begin(); |
| 84 | it != data->promises.end(); |
| 85 | ++it) { |
| 86 | if ((*it)->future() == future) { |
no outgoing calls
no test coverage detected