How to immediately start a thread in C++?

To create and immediately run a thread in C++, you can use the std::thread class and then call the join() method right after creating the thread to wait for it to finish execution. Here is a simple example code:

#include <iostream>
#include <thread>

void myThreadFunction() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread myThread(myThreadFunction); // 创建线程并指定线程函数
    myThread.join(); // 等待线程执行完毕

    std::cout << "Main thread is done!" << std::endl;

    return 0;
}

In the example above, a thread named myThread is created and the myThreadFunction function is called within it. The join() method is then immediately invoked to wait for the thread to finish executing. This ensures that the thread starts running right away, and the main thread waits for it to finish before continuing execution.

Leave a Reply 0

Your email address will not be published. Required fields are marked *