2

I have a class main.cpp, as well as MyClass.cpp.

In main.cpp, I have a lot of code. At the top though, I create a MyClass object and then I'd like to start a thread that is in MyClass. I'd like it to call a function Run() and have the function run at the same time that the rest of the functions in main.cpp run.

What is the easiest way to do this in C++. I've never done threading in C++, however I have done so in Java.

I'd like to avoid using external packages and such if possible.

4

3 に答える 3

4

最も簡単な方法は、ブースト スレッドライブラリを使用することです。

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

...

int main()
{
  ...
  MyClass mc;
  boost::thread bt(boost::bind(MyClass::Run, &mc));
  ...
  bt.join();
  ...
 }
于 2012-04-13T00:15:05.790 に答える
2

C++ 言語自体には、スレッドの概念はありません*。確かに C++ でマルチスレッド プログラムを作成できますが、プラットフォーム固有のスレッド ライブラリを使用する必要があります。たとえば、Linux システムでは「pthreads」ライブラリを使用できます。ターゲット プラットフォームは何ですか?

*新しい C++11 仕様で追加された拡張機能により、スレッドの標準化されたサポートが追加されますが、多くのコンパイラと標準ライブラリは、このバージョンの標準をまだ実装していません。

于 2012-04-13T00:13:39.053 に答える