Sobes.tech
Junior — Middle

How is a new thread of execution started in a program?

sobes.tech AI

Answer from AI

In C/C++, creating a new thread of execution is usually done using the standard <thread> library (since C++11). An std::thread object is created, to which a function or functor is passed for execution in the new thread.

Example:

#include <iostream>
#include <thread>

void task() {
    std::cout << "Thread is running" << std::endl;
}

int main() {
    std::thread t(task); // start a new thread
    t.join(); // wait for the thread to finish
    return 0;
}

In C, POSIX threads (pthread) can be used, where a thread is created via pthread_create.