0

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;
    }
};
PentiumPro200
  • 641
  • 7
  • 23
  • 2
    You instance the `std::thread threadObj1` as local variable in the constructor `Wrapper::Wrapper()`. It is destroyed as soon as the constructor is left. This should (IMHO) be a member variable of `Wrapper` instead. – Scheff's Cat Dec 13 '19 at 06:22
  • @Scheff, thanks, that fixed it. I made the correction to the code above. I'll close this question. – PentiumPro200 Dec 13 '19 at 15:38

1 Answers1

0

@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.

PentiumPro200
  • 641
  • 7
  • 23