首页 > 解决方案 > C++ 阻塞队列线程

问题描述

我编写了一个简单的类,我计划将其扩展为客户端套接字编程应用程序的一部分。该类涉及一个 BlockingQueue(我从这里复制了代码:C++ Equivalent to Java's BlockingQueue)。一旦我在下面创建了 Wrapper 类的实例,我打算让它产生一个单独的线程,该线程简单地执行在 BlockingQueue 上阻塞的打印机()函数,直到一个或多个字符串可用,然后它只是将字符串打印到控制台窗口。在我的预期应用程序中,控制台打印将替换为更耗时的网络功能,包括发送数据包、等待接收方的确认和一些错误处理。但是现在,我只是想让它打印到控制台窗口而不会崩溃。当我执行时,它会在打印任何内容之前立即崩溃。

#include <iostream>
#include <thread>
#include "BlockingQueue.h"

using namespace std;

class Wrapper {

  public:
      Wrapper() {
          threadObj1 = thread(&Wrapper::printer, this);
      }

      void submitStringToWrite(string str) {
          queue.push(str);
      }

      void printer() {
          while(true) {
              string str = queue.pop();
              cout << str.c_str() << endl;
          }
      }

    private:
        BlockingQueue<string> queue;
        std::thread threadObj1;
};

int main() {
  Wrapper *w = new Wrapper();
  w->submitStringToWrite("One");
  w->submitStringToWrite("Two");
  w->submitStringToWrite("Three");
  system("pause");
  return 0;
}

这是从上面的链接借用的阻塞队列实现:

#include <mutex>
#include <condition_variable>
#include <deque>

template <typename T>
class BlockingQueue
{
private:
    std::mutex              d_mutex;
    std::condition_variable d_condition;
    std::deque<T>           d_queue;
public:
    void push(T const& value) {
        {
            std::unique_lock<std::mutex> lock(this->d_mutex);
            d_queue.push_front(value);
        }
        this->d_condition.notify_one();
    }
    T pop() {
        std::unique_lock<std::mutex> lock(this->d_mutex);
        this->d_condition.wait(lock, [=]{ return !this->d_queue.empty(); });
        T rc(std::move(this->d_queue.back()));
        this->d_queue.pop_back();
        return rc;
    }
};

标签: c++multithreadingblockingqueue

解决方案


@Scheff 在评论部分的回答是正确的。我修复了上面的代码。现在可以了。我无法再关闭 2 天的问题。版主,您可以继续并关闭此问题。


推荐阅读