boost::mutex,
boost::mutex::scoped_lock,
boost::condition

boost のスレッド関連ユーティリティです。
boost::thread を使用する場合、これらは必需品となるでしょう。まぁ、mutexにこだわる理由事態はありませんが、今現在は critical section に相当するものを boost で見つけられないので、まぁ当面はこの mutex を使用することになるでしょう。名前付きの mutex にもできるのかしら?

[サンプルソース]

#include <iostream>
#include <string>
#include <boost/ref.hpp>
#include <boost/thread.hpp> // boost::thread, boost::mutex, boost::mutex::scoped_lock
#include <boost/thread/condition.hpp>
// boost::condition

using namespace std;

class urger
{
    volatile bool end_flag ;
    typedef boost::mutex::scoped_lock lock ;
    boost::mutex ef_guard ;
    boost::condition exitRequest ;

public:
    urger() : end_flag(false)
    {
    }

    void operator()()
    {
        // 基本的に無限ループしておく
        for (;;){
            lock lk( ef_guard );

 
           // 終了通知を受けてたらループを終了
            if ( end_flag ){
                break ;
            }

            // 現在の5秒後の時間を計算
            boost::xtime xt ;
            boost::xtime_get( &xt, boost::TIME_UTC );
            xt.sec += 5 ;

            // 終了通知を待ちます。ただし5秒たったら待ち解除
            if ( exitRequest.timed_wait( lk, xt )){
                break ;
            }
            else{
                cout << "n何か書くのじゃー!:" << flush ;
            }
        }
    }

    void exit()
    {
        // 終了を通知します。
        lock lk(ef_guard);
        end_flag = true ;
        exitRequest.notify_one();
    }
};

int main(int argc, char* argv[])
{
    urger u ;
    boost::thread thr( boost::ref(u) );

    // 入力待ち
    cout << "何か書いてね: " ;
    string str ;
    getline( cin, str );

    // 入力が終わったら、スレッドを終了して欲しいことをスレッドへ通知
    u.exit();

    // 催促スレッドの終了待ち
    thr.join();

    cout << "Thank you!" << endl;

    return 0;
}


記載: 2010年3月26日 木下英俊