比較的長時間実行されるスキャン手順をトリガーする「スキャン」メソッドを持つ C++ プログラムを開発しています。手順が完了すると、scan メソッドはオブザーバー パターンを使用して結果をオブザーバーに通知します。
スキャンごとに個別のスレッドを作成したいと思います。このようにして、複数のスキャンを同時に実行できます。各スキャン プロセスが完了すると、スキャン メソッドがリスナーに通知するようにします。
ブースト スレッド ライブラリによると、次のようなことができるようです。
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <iostream>
boost::mutex io_mutex;
void scan(int scan_target, vector<Listener> listeners)
{
//...run scan
{
boost::mutex::scoped_lock
lock(io_mutex);
std::cout << "finished scan" << endl;
// notify listeners by iterating through the vector
// and calling "notify()
}
}
int main(int argc, char* argv[])
{
vector<Listener> listeners
// create
boost::thread thrd1(
boost::bind(&scan, 1, listeners));
boost::thread thrd2(
boost::bind(&scan, 2, listeners));
//thrd1.join();
//thrd2.join();
return 0;
}
これはおおよそ正しいように見えますか? リスナーへの呼び出しをミューテックスする必要がありますか? 結合をなくしても大丈夫ですか?