是否使用unique_ptr成员变量?

时间:2017-06-04 18:34:36

标签: c++ multithreading c++11 blockingqueue

什么是更好的设计模式来创建阻塞缓冲区,它在C ++ 11/14中有效地使用资源而没有太多的分配/移动?使用Queue<std::unique_ptr<Workitem>>

OR

Queue<Workitem>并将其隐藏在实现中的资源管理(有点像stl容器)。注意,第二个想法(队列)被注释掉了。注释版本对堆/堆栈的影响是什么?那么使用std::unique_ptr<Queue<Workitem>> q呢?

我对c ++不太满意,但无论版本如何,我都无法真正泄露内存吗? (reasonging:not new / delete - &gt; no memoryleaks)

代码在这里:

#include <condition_variable>
#include <mutex>
#include <queue>

template <class T> class Queue {
public:
  Queue(size_t size);

  // push item to _queue if _queue.size() < _size
  // else block
  void push(T item);
  // void push(std::unique_ptr<T> item);

  // pop item if !_queue.empty()
  // else block or return false after timeout
  bool pop(T &item);
  // bool pop(std::unique_ptr<T> &item);

private:
  std::mutex _mutex;
  std::size_t _size;

  std::queue<T> _queue;
  // std::queue<std::unique_ptr<T>> _queue;

  std::condition_variable _condition_full;
  std::condition_variable _condition_empty;
};

struct Workitem {
  size_t idx;
  void *workdetails;
};

void do_work(Queue<std::unique_ptr<Workitem>> &work_q,
             Queue<std::unique_ptr<Workitem>> &write_q,
             struct options_s &opts) {
  std::unique_ptr<Workitem> work;
  while (work_q.pop(work)) {
    // calculation w/ work
    std::unique_ptr<Workitem> res = consume(work, opts);
    write_q.push(std::move(work));
  }
}
void do_write(Queue<std::unique_ptr<Workitem>> &write_q,
              struct options_s &opts) {
  std::unique_ptr<Workitem> work;
  while (write_q.pop(work)) {
    prepare_for_writing(work, opts); // clean item
    write(work);
  }
}

auto w1 = std::thread(do_work, std::ref(work_q), std::ref(write_q),
                      std::ref(options));
auto w2 = std::thread(do_work, std::ref(work_q), std::ref(write_q),
                      std::ref(options));
auto writer = std::thread(do_write, std::ref(write_q), std::ref(options));

int main() {
  Queue<std::unique_ptr<Workitem>> work_q{4};
  Queue<std::unique_ptr<Workitem>> write_q{4};
  // Queue<Workitem> q{4};
  // ??? std::unique_ptr<Queue<Workitem>> q{4} ???

  for (size_t i, ...) { // do many iterations
    std::unique_ptr<Workitem> w{};
    // Workitem w{};

    populate(w, i); // populate work item

    work_q.push(std::move(w));
  }

  w1.join();
  w2.join();
  writer.join();
}

如果有帮助的话,我可以给出实施,我只是不想让所有东西混乱,所以我把它留了出来。作为注释,队列由线程使用。我为多个工作线程使用两个队列,并使用一个写入器线程将负载分散到核心。

欢呼声

1 个答案:

答案 0 :(得分:2)

  

什么是更好的设计模式来创建阻塞缓冲区,它在C ++ 11/14中有效地使用资源而没有太多的分配/移动?使用Queue<std::unique_ptr<Workitem>>Queue<Workitem>

鉴于该标准,Queue<Workitem>更好,因为它避免了一层动态分配。

  

注释掉版本对堆/堆栈的影响是什么?

堆与堆栈之间没有任何差异。这些对象在两种变体中都是动态分配的。

  

我真的无法泄露记忆吗? (reasonging:not new / delete - &gt; no memoryleaks)

你的推理是合理的。您显示的示例代码没有内存泄漏。

但是有一个裸指针成员变量Workitem::workdetails,如果它被滥用(如果它拥有它所指向的内存),则可能存在内存泄漏的可能性。