Search code examples
c++multithreading

How to run method/function on a separate thread in c++


I am a beginner in C++, so I don't know much.

Here is a function I have:

void example() {
     for(int i = 0; i < 5; i++) {
          // do stuff
     }
}

If I call this function, it will wait for it to be finished before continuing:

int main() {
     example();

     otherThingsGoHere();
     otherThingsGoHere();
     otherThingsGoHere();

     return 0;
}

The otherThingsGoHere() doesn't get called until example() is done.

My goal is to have that function be able to loop 60/70 fps in a loop forever.

And I did get it working, except nothing below that will happen since it is in an infinite loop.

I've been a C# developer for some time and I know that in c#, you can use async functions to run on a separate thread. How do I implement something like this in C++?

Edit: I am not asking for you to put the otherThingsGoHere in front of the main because the other things is going to be another loop, so I need both of them to run at the same time


Solution

  • You can use a std::thread and run the example() function from that new thread.

    A std::thread can be started when constructed with a function to run. It will run potentially in parallel to the main thread running the otherThingsGoHere. I wrote potentially because it depends on your system and number of cores. If you have a PC with multiple cores it can actually run like that. Before main() exits it should wait for the other thread to end gracefully, by calling std::thread::join().

    A minimal example for your case would be:

    #include <thread>
    #include <iostream>
    #include <chrono>
    
    void example() {
        for (int i = 0; i < 5; i++) {
            std::cout << "thread...\n";
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
    }
    
    void otherThingsGoHere() {
        std::cout << "do other things ...\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    
    int main() {
        std::thread t{ example };
    
        otherThingsGoHere();
        otherThingsGoHere();
        otherThingsGoHere();
    
        t.join();
        return 0;
    }