Home > front end >  How to run method/function on a separate thread in c
How to run method/function on a separate thread in c

Time:04-24

I am a beginner to c , so I don't know much

here is a function

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 seperate thread. How do I impliment 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

CodePudding user response:

You need to 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 thread::join().

A minimal example for your case would be:

#include <thread>
#include <iostream>

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;
}

Some more info here: Simple example of threading in C

  • Related