Home > Article > Backend Development > How to create thread in C++?
Creating threads can improve program performance and responsiveness. In C++, create a thread using the std::thread(function_name, argument_list) syntax, where function_name is the function to be run and argument_list are the arguments to be passed. For example, create a thread to print "Hello, World!": #include How to create a thread in C++ Threads are lightweight execution units that can run simultaneously with other threads. Each thread has its own independent instruction pointer, stack and local variables. Creating threads improves your program's performance and responsiveness by increasing concurrency and maximizing CPU utilization. Syntax for creating threads In C++, we can use the following syntax to create threads: Among them, Practical case: Create and run a thread The following is a practical case of creating a new thread and making it print "Hello, World!": In this case, the Things to notestd::thread thread_name(function_name, argument_list);
thread_name
is the name of the thread object, function_name
is the function to be run, and argument_list
is the argument list to be passed to the function. #include <iostream>
#include <thread>
using namespace std;
void printMessage() {
cout << "Hello, World!" << endl;
}
int main() {
// 创建一个新线程
thread thread1(printMessage);
// 让主线程等待子线程完成
thread1.join();
return 0;
}
printMessage
function is a simple function to be executed by the new thread. thread1.join()
statement will block the main thread until the child thread completes execution.
The above is the detailed content of How to create thread in C++?. For more information, please follow other related articles on the PHP Chinese website!