Question: C++ Threads Need help with witty program. Program named witty.cpp reads line from a text file called wittylines.txt and outputs a witty line every 5

C++ Threads

Need help with witty program. Program named witty.cpp reads line from a text file called wittylines.txt and outputs a witty line every 5 seconds. We would like it so if we press a key and enter, then to make the program stop. Need help running the Wittylines class in a thread. This means moving or calling the showOneLiners() function in an operator()() function, then modify main so it runs the class in a thread. A pointer to the stop variable is sent to the thread object in the constructor. When the stop variable is set, the showOneLiners loop should stop (it will have to wait until the remainder of the 5 seconds elapses). However, the code will crash because the main thread will exit before the Wittylines thread. Make the main function wait for the thread to finish by adding the join function call before your program exits. The program should now quit after typing a key (like 'q') and hitting enter. Program needs to compile with -std=c++11 flag and also the -lpthread flag.

#include  #include  #include  #include  #include  #include  #include  #include  using namespace std; class Wittylines { public: Wittylines(bool *stop); void showOneLiners(); private: bool *stop; vector one_liners; }; Wittylines::Wittylines(bool *stop) { this->stop = stop; *(this->stop) = false; ifstream data; data.open("wittylines.txt"); if (data.fail()) { cout << "Error opening file." << endl; return; } string s; while (getline(data, s)!=NULL) one_liners.push_back(s); data.close(); } void Wittylines::showOneLiners() { while (!(*stop)) { int r = rand() % one_liners.size(); cout << one_liners[r] << endl; std::this_thread::sleep_for(std::chrono::seconds(5)); } } int main() { bool stop = false; srand(time(NULL)); Wittylines witty(&stop); witty.showOneLiners(); char c; cin >> c; stop = true; return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!