C++ std::thread Guide: Usage & Examples
std::thread is a class in the C++11 standard library that is used for creating and managing threads. It allows for the creation of a new thread and passing a callable object (function, function object, or lambda expression) as a parameter to the thread.
When using std::thread, you need to include the header file, and the thread object can be initialized using the constructor. For example:
#include <iostream>
#include <thread>
void threadFunc() {
std::cout << "Hello from thread" << std::this_thread::get_id() << std::endl;
}
int main() {
std::thread threadObj(threadFunc);
// 等待线程执行完成
threadObj.join();
std::cout << "Main thread" << std::this_thread::get_id() << " exiting..." << std::endl;
return 0;
}
In the example above, a thread object named threadObj is created using std::thread and the function threadFunc is passed as a callable object to this thread. The join() method is then called in the main thread to wait for the thread to finish execution. Finally, the main thread’s ID and exit information are printed.
In addition to using the join() method, you can also use the detach() method to detach threads and allow them to run independently. It is important to consider thread safety and resource management when using std::thread.