C++ クラスのメンバーである pthread を開始する最良の方法を知りたいですか? 私自身のアプローチは答えとして続きます...
5 に答える
これは、次のように boost ライブラリを使用して簡単に実行できます。
#include <boost/thread.hpp>
// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}
// construct an instance of the widget modeller or controller
cWidget theWidget;
// start new thread by invoking method run on theWidget instance
boost::thread* pThread = new boost::thread(
&cWidget::Run, // pointer to member function to execute in thread
&theWidget); // pointer to instance of class
ノート:
- これは、通常のクラス メンバー関数を使用します。クラス インターフェイスを混乱させる余分な静的メンバーを追加する必要はありません。
- スレッドを開始するソース ファイルに boost/thread.hpp を含めるだけです。ブーストを始めたばかりの場合、その大きくて威圧的なパッケージの残りはすべて無視できます.
C++11 でも同じことができますが、boost は必要ありません
// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}
// construct an instance of the widget modeller or controller
cWidget theWidget;
// start new thread by invoking method run on theWidget instance
std::thread * pThread = new std::thread(
&cWidget::Run, // pointer to member function to execute in thread
&theWidget); // pointer to instance of class
私は通常、クラスの静的メンバー関数を使用し、クラスへのポインターをvoid*パラメーターとして使用します。その関数は、スレッド処理を実行するか、クラス参照を使用して別の非静的メンバー関数を呼び出すことができます。その関数は、厄介な構文なしですべてのクラスメンバーを参照できます。
void*パラメータを使用してブートストラップする必要があります。
クラスA {{ static void * StaticThreadProc(void * arg) {{ reinterpret_cast <A *>(arg)-> ThreadProc();を返します。 } void * ThreadProc(void) {{ //何かをする } }; ..。 pthread_t theThread; pthread_create(&theThread、NULL、&A :: StaticThreadProc、this);
上記の3つの方法を使用しました。私が最初に c++ でスレッド化を使用したときは、静的メンバ関数を使用し、次にフレンド関数を使用し、最後にBOOST ライブラリを使用しました。現在、私はBOOSTを好みます。過去数年間、私はかなりの BOOST 偏見になりました。
CPAN が Perl に対するものであるように、BOOST は C++ に対するものです。:)
Boostライブラリは、オブジェクト情報を新しいスレッドに転送するのに役立つコピーメカニズムを提供します。他のブーストの例では、boost :: bindはポインターとともにコピーされ、これもコピーされます。したがって、ダングリングポインタを防ぐために、オブジェクトの有効性に注意する必要があります。operator()を実装し、代わりにコピーコンストラクターを提供してオブジェクトを直接渡す場合は、それを気にする必要はありません。
多くのトラブルを防ぐ、はるかに優れたソリューション:
#include <boost/thread.hpp>
class MyClass {
public:
MyClass(int i);
MyClass(const MyClass& myClass); // Copy-Constructor
void operator()() const; // entry point for the new thread
virtual void doSomething(); // Now you can use virtual functions
private:
int i; // and also fields very easily
};
MyClass clazz(1);
// Passing the object directly will create a copy internally
// Now you don't have to worry about the validity of the clazz object above
// after starting the other thread
// The operator() will be executed for the new thread.
boost::thread thread(clazz); // create the object on the stack
もう1つのブーストの例では、ヒープ上にスレッドオブジェクトを作成しますが、それを行う意味はありません。