简体   繁体   中英

How to make a basic thread in C++

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.

The simplest way for you to go is to use boost thread library.

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

...

int main()
{
  ...
  MyClass mc;
  boost::thread bt(boost::bind(MyClass::Run, &mc));
  ...
  bt.join();
  ...
 }

The C++ language itself doesn't have any notion of threads*. You can certainly write multithreaded programs in C++, but it will involve using a platform-specific thread library. For example, you can use the "pthreads" library on Linux systems. What is your target platform?

*The extensions added in the new C++11 spec add standardized support for threads, but many compilers and standard libraries do not yet implement this version of the standard.

Using standard C++:

#include <future>

int main() {
    MyClass mc;
    auto future = std::async(MyClass::Run,&mc);
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM