queue.h 1.6 KB
Newer Older
1
/**
2
3
4
5
6
7
8
9
10
 * Copyright (c) Facebook, Inc. and its affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */
#ifndef DGL_RPC_TENSORPIPE_QUEUE_H_
#define DGL_RPC_TENSORPIPE_QUEUE_H_

11
#include <dmlc/logging.h>
12
13

#include <chrono>
14
15
16
#include <condition_variable>
#include <deque>
#include <mutex>
17
#include <utility>
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

namespace dgl {
namespace rpc {

template <typename T>
class Queue {
 public:
  // Capacity isn't used actually
  explicit Queue(int capacity = 1) : capacity_(capacity) {}

  void push(T t) {
    std::unique_lock<std::mutex> lock(mutex_);
    // while (items_.size() >= capacity_) {
    //   cv_.wait(lock);
    // }
    items_.push_back(std::move(t));
    cv_.notify_all();
  }

37
  bool pop(T *msg, int timeout) {
38
    std::unique_lock<std::mutex> lock(mutex_);
39
40
41
42
    if (timeout == 0) {
      DLOG(WARNING) << "Will wait infinitely until message is popped...";
      cv_.wait(lock, [this] { return items_.size() > 0; });
    } else {
43
44
45
      if (!cv_.wait_for(lock, std::chrono::milliseconds(timeout), [this] {
            return items_.size() > 0;
          })) {
46
47
48
49
        DLOG(WARNING) << "Times out for popping message after " << timeout
                      << " milliseconds.";
        return false;
      }
50
    }
51
    *msg = std::move(items_.front());
52
53
    items_.pop_front();
    cv_.notify_all();
54
    return true;
55
56
57
58
59
60
61
62
63
64
65
66
  }

 private:
  std::mutex mutex_;
  std::condition_variable cv_;
  const int capacity_;
  std::deque<T> items_;
};
}  // namespace rpc
}  // namespace dgl

#endif  // DGL_RPC_TENSORPIPE_QUEUE_H_