2016-10-12 18 views
0

代碼:多線程活動檢查不顯示任何信息

#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庫瞎搞,並希望讓使用線程和互斥事件檢查。出於某種原因,沒有輸出,即使在主線程中,它應該打印「任何人」。我正在使用Mac OSX和Xcode。程序編譯並運行得很好。

+2

您可能希望搜索*條件變量*,並學習如何使用它們 – WhiZTiM

回答

1

正如已經@krzaq主循環不打印任何提及,因爲join等待線程,這永遠不會發生的終止是由於t_1t_2無端環。

至於您的t_1輸出:您的輸出中沒有換行符。通常情況下,輸出緩衝區僅在換行符上刷新,這意味着在打印換行符或填充緩衝區之前,不會看到輸出結果被刷新到終端。

試試這個:

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

在主線程的打印循環之前,你的線程永遠不會完成,並且它們(即等待它們完成)。

t1.join(); // the main thread never gets past this point 
+0

,我應該使用分離()呢? – Ricky