Richter B. Richter B. - 1 month ago 6
C++ Question

Multi-threaded event checker does not print anything

Code:

#include <iostream>
#include <future>
#include <queue>
#include <boost/thread/thread.hpp>

boost::mutex mtx;

std::queue<std::string>ev;

void t_1(){
while(true){
mtx.lock();
if(ev.size() > 0){
std::cout << ev.front();
ev.pop();
}
mtx.unlock();
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
}
}

void t_2(){
int x = 0;
while(true){
x++;
mtx.lock();
ev.push("new event");
mtx.unlock();
boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
}
}

void t_3(){
while(true){
std::cout << 3;
}
}

int main(int argc, const char * argv[]) {
// insert code here...
boost::thread t1(t_1);
boost::thread t2(t_2);
//boost::thread t3(t_3);
t1.join();
t2.join();
while(true){
std::cout << "anyone there";
}
//t3.join();
return 0;
}


I was messing around with the boost library, and wanted to make an event checker using threads and mutexes. For some reason there is no output, even on the main thread when it should print "anyone there." I am using Mac OSX and Xcode. THe program compiles and runs just fine.

Answer

As already mentioned by @krzaq your main loop does not print anything because join waits for the termination of the thread, which will never happen due to the endless loops in t_1 and t_2.

As for your t_1 output: You have no newline in your output. Typically the output buffer is flushed only on a newline, which means that you will not see the output flushed to your terminal until you either print a newline or the buffer is filled up.

Try this:

std::cout << ev.front() << "\n";
Comments