boost庫:多線程


1.線程管理

最重要的一個類是boost::thread,是在boost/thread.hpp里定義的,用來創建一個新線程。

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

void wait(int seconds) {
  boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}

void thread() {
  for (int i = 0; i < 5; ++i) {
    wait(1);
    std::cout << i << std::endl;
  }
}

int main() {
  boost::thread t(thread);
  t.join();
  return 0;
}

上述執行函數的名稱被傳遞到boost::thread的構造函數,一旦變量t被創建,該thread()函數在其所在線程中被立即執行。join()方法是一個阻塞調用:可以暫停當前線程,直到調用join()的線程結束與你想那個。這會使得main()函數一直會等待到thread()運行結束。

一個特定的線程可以通過thread變量訪問,通過這個變量等待着它的使用join()方法終止,但即使該變量被析構,該線程也將繼續運行。

 

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

void wait(int seconds) {
  boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}

void thread() {
  try {
    for (int i = 0; i < 5; ++i) {
      wait(1);
      std::cout << i << std::endl;
    }
  } catch (boost::thread_interrupted&) {
   }
}

int main() {
  boost::thread t(thread);
  wait(3);
  t.interrupt();
  t.join();
  return 0;
}

在一個線程對象上調用interrupt()會中斷相應的線程。中斷意味着一個類型為boost::thread_interrupted的異常,會在這個線程中拋出,只有在線程達到中斷點時才會發生。如果給定的線程不包含任何中斷點,簡單調用interrupt()就不會起作用。每當一個線程中斷點,它就會檢查interrupt()是否被調用過。只有被調用過了,boost::thread_interrupted異常才會相應的拋出。sleep()函數為一個程序中斷點。

2. 同步

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM