简体   繁体   中英

C++ Blocking Queue Threading

I wrote a simple class which I plan to extend as part of a client socket programming application. The class involves a BlockingQueue (I copied the code from here: C++ Equivalent to Java's BlockingQueue ). Once I create an instance of the Wrapper class below, I intended to have it spawn off a separate thread which simply executes the printer() function that blocks on the BlockingQueue until one or more strings are available and then it simply prints the string to the console window. In my intended application, the console print will be replaced with a more time-consuming network function that involves sending packets, waiting for acknowledgement from the receiver and some error handling. But for now, I'm just trying to get it to print to the console window without crashing. When I execute, it immediately crashes before printing anything.

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

Here is the blocking queue implementation, borrowed from link above:

#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's answer in the comment section is correct. I fixed the code above. It works now. I'm not able to close the question for another 2 days. Moderators, you can go ahead and close this question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM