代码:
#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;
}
我正在搞乱升级库,并希望使用线程和互斥锁进行事件检查。由于某种原因没有输出,即使在主线程上它应该打印&#34;任何人在那里。&#34;我正在使用Mac OSX和Xcode。程序编译并运行得很好。
答案 0 :(得分:1)
您的主题永远不会完成,并且在主线程中的打印循环之前,您join()
(即等待它们完成)。
t1.join(); // the main thread never gets past this point
答案 1 :(得分:1)
正如@krzaq已经提到的,你的主循环不会打印任何东西,因为join
等待线程的终止,由于t_1
和{{1}中的无限循环而永远不会发生这种情况}。
至于您的t_2
输出:您的输出中没有换行符。通常,输出缓冲区仅在换行符上刷新,这意味着在打印换行符或填充缓冲区之前,您不会看到刷新到终端的输出。
试试这个:
t_1