I have a class which executes a thread in order to constantly read lines from a given istream, which are then parsed internally. At some point I want it to end, but since the getline() call is blocking, it may wait forever on join().
#pragma once
#include <thread>
#include <iostream>
class Parser {
private:
std::istream& input;
std::thread parserThread;
public:
Parser(std::istream& input_) : input(input_)/* ... */{}
~Parser() {
stop();
}
void start() {
// Avoid multiple threads...
parserThread = std::thread(&Parser::monitorThread, this);
}
void stop() {
continueParsing = false;
parserThread.join(); // Wait for it to finish
continueParsing = true; // Allow to start another thread at a later point
}
private:
void monitorThread() {
std::string buffer;
// Constantly reads new input until it's told to stop
while(std::getline(input, buffer) && continueParsing) {
//...
}
}
};
Is there any standard way to accomplish this? Or is my approach (have a thread reading forever) wrong? If it were C I would just kill the thread...