web-dev-qa-db-ja.com

boost :: threadに引数を渡す方法は?

thread_ = boost::thread( boost::function< void (void)>( boost::bind( &clientTCP::run , this ) ) );  

runに次のような引数がある可能性はありますか?

void clientTCP::run(boost:function<void(std::string)> func);

はいの場合、boost :: thread呼び出しをどのように書くべきか

ありがとう。

19
Guillaume07

次のコードboost::bind( &clientTCP::run , this )は、関数のコールバックを定義します。現在のインスタンス(run)で関数thisを呼び出します。 boost :: bindを使用すると、次のことができます。

// Pass pMyParameter through to the run() function
boost::bind(&clientTCP::run, this, pMyParameter)

こちらのドキュメントと例をご覧ください。
http://www.boost.org/doc/libs/1_46_1/doc/html/thread/thread_management.html

引数を指定する必要がある関数または呼び出し可能オブジェクトを使用してboost :: threadのインスタンスを作成する場合は、追加の引数をboost :: threadコンストラクターに渡すことで実行できます。

void find_the_question(int the_answer);

boost::thread deep_thought_2(find_the_question,42);

お役に立てば幸いです。

31
Mark Ingram

将来の作業のために、Boostはデフォルトで引数を値で渡すことに注意したかっただけです。したがって、参照を渡したい場合は、boost::ref()メソッドとboost::cref()メソッドがあり、後者は定数参照用です。

参照にはまだ&演算子を使用できると思いますが、よくわかりません。私は常にboost::refを使用しています。

8
Adri C.S.
thread_ = boost::thread( boost::function< void (void)>( boost::bind( &clientTCP::run , this ) ) );  

bindandfunctionは不要であり、コードが遅くなり、より多くのメモリを使用します。ただしてください:

thread_ = boost::thread( &clientTCP::run , this );  

引数を追加するには、引数を追加するだけです。

thread_ = boost::thread( &clientTCP::run , this, f );  
6
Jonathan Wakely