簡體   English   中英

C++ 阻塞隊列線程

[英]C++ Blocking Queue Threading

我編寫了一個簡單的類,我計划將其擴展為客戶端套接字編程應用程序的一部分。 該類涉及一個 BlockingQueue(我從這里復制了代碼: C++ Equivalent to Java's BlockingQueue )。 一旦我在下面創建了 Wrapper 類的實例,我打算讓它從一個單獨的線程中產生,該線程只執行在 BlockingQueue 上阻塞的 printer() 函數,直到一個或多個字符串可用,然后它只是將字符串打印到控制台窗口。 在我預期的應用程序中,控制台打印將替換為更耗時的網絡功能,包括發送數據包、等待接收方的確認和一些錯誤處理。 但是現在,我只是想讓它在不崩潰的情況下打印到控制台窗口。 當我執行時,它會在打印任何內容之前立即崩潰。

#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;
    }
};

@Scheff 在評論部分的回答是正確的。 我修復了上面的代碼。 它現在有效。 我無法再結束 2 天的問題。 版主,你可以繼續關閉這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM