Sobes.tech
Junior — Middle

How can a separate thread be initiated in a program?

sobes.tech AI

Answer from AI

In C++, the std::thread class from the <thread> standard library is usually used to start a separate thread. To initiate thread execution, an std::thread object is created, passing it a function or functor that should run in the new thread.

Example:

#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Thread started" << std::endl;
}

int main() {
    std::thread t(threadFunction); // create and start the thread
    t.join(); // wait for the thread to finish
    return 0;
}

It is also possible to use functions from POSIX Threads (pthread) in C, but in modern C++, std::thread is preferred.