多线程事件检查器不打印任何东西
Multi-threaded event checker does not print anything
代码:
#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;
}
我正在研究 boost 库,想使用线程和互斥体制作一个事件检查器。由于某种原因没有输出,即使在主线程上应该打印 "anyone there." 我正在使用 Mac OSX 和 Xcode。该程序编译并运行得很好。
您的线程永远不会完成,而您 join()
在主线程中的打印循环之前(即等待它们完成)。
t1.join(); // the main thread never gets past this point
正如@krzaq 已经提到的,您的主循环不会打印任何内容,因为 join
等待线程终止,由于 t_1
和 [= 中的无限循环,这种情况永远不会发生13=].
至于您的 t_1
输出:您的输出中没有换行符。通常,输出缓冲区仅在换行时刷新,这意味着在打印换行符或缓冲区填满之前,您不会看到输出刷新到终端。
试试这个:
std::cout << ev.front() << "\n";
代码:
#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;
}
我正在研究 boost 库,想使用线程和互斥体制作一个事件检查器。由于某种原因没有输出,即使在主线程上应该打印 "anyone there." 我正在使用 Mac OSX 和 Xcode。该程序编译并运行得很好。
您的线程永远不会完成,而您 join()
在主线程中的打印循环之前(即等待它们完成)。
t1.join(); // the main thread never gets past this point
正如@krzaq 已经提到的,您的主循环不会打印任何内容,因为 join
等待线程终止,由于 t_1
和 [= 中的无限循环,这种情况永远不会发生13=].
至于您的 t_1
输出:您的输出中没有换行符。通常,输出缓冲区仅在换行时刷新,这意味着在打印换行符或缓冲区填满之前,您不会看到输出刷新到终端。
试试这个:
std::cout << ev.front() << "\n";