[Boost] ASIO學習筆記:thread及Synchronization

posted in: ASIO, boost, C/C++程式設計 | 0

我們知道,我們無法預測thread執行的先後,這代表的是任何一個thread都有可以在任何的時間點從CPU上取得操作權。這不僅會造成cout時文字無法連續,同時在操作資料時,最害怕的情形是『同時』有多個thread去對『同一個資料』做更改,因為他會造成運算結果的錯誤。這個特性,在電腦科學裡面稱作race condition,進而導致了需要保證thread-safety的問題。

在boost裡提供了mutex機制來解決(Critical Section Problem)

一個簡單的demo:

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

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

boost::mutex mutex; 

int gValue = 0;
void thread(int i) 
{ 
    wait(1); 
    mutex.lock(); 
    gValue = gValue + i;
    std::cout < < "Thread :" << boost::this_thread::get_id() << ": gValue + " << i << " =" <<  gValue << std::endl; 
    mutex.unlock(); 
} 

int main() 
{ 
    boost::thread t1(boost::bind(&thread, 1)); 
    boost::thread t2(boost::bind(&thread,2)); 
    t1.join(); 
    t2.join(); 
    std::cout << "finally gValue:" << gValue << std::endl;
    system("pause");
} 

當我們下了mutex.lock(); 之後,所有的thread都會停止,直到mutex.unlock();

lock主要分為exclusive locks及non-exclusive locks等二種。

例如:

boost::mutex

boost::lock_guard lock(mutex);

boost::unique_lock lock(mutex, boost::try_to_lock);

boost::unique_lock lock(mutex);

boost::shared_lock lock(mutex);

在thread programming中,還有一個重要的概念:Thread Local Storage,說明我們該怎麼樣把原本宣告成會所有thread共享的全域或靜態變數的變數,變成每個thread會保有一份的local變數。在boost中,提供了boost::thread_specific_ptr來實現這個概念,以下為一個簡單的範例:

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


boost::thread_specific_ptr tls; 
void thread(int i){
    tls.reset(new int(i));
}


int main() { 
    boost::thread t[3]; 
    tls.reset(new int(1));
    for (int i = 0; i < 3; ++i) 
      t[i] = boost::thread(boost::bind(&thread, i)); 

    for (int i = 0; i < 3; ++i) 
    t[i].join(); 

    std::cout << *tls.get() << std::endl;
    system("pause");
 } 

Leave a Reply

Your email address will not be published. Required fields are marked *