In C++, multithreading allows programs to perform multiple tasks concurrently. The std::thread
class, available in the C++11 standard and later, provides a simple and efficient way to create and manage threads in C++.
Creating a Thread
To create a new thread, we can instantiate an std::thread
object and pass a function to be executed by the new thread.
#include <iostream>
#include <thread>
void myFunction() {
// Do some work in the new thread
std::cout << "Hello from the new thread!" << std::endl;
}
int main() {
// Create a new thread
std::thread myThread(myFunction);
// Do some work in the main thread
std::cout << "Hello from the main thread!" << std::endl;
// Wait for the new thread to finish
myThread.join();
return 0;
}
In this example, we create a new thread by passing the myFunction
to the std::thread
constructor. The main thread continues to execute its work, and at the end, it waits for the new thread to finish by calling myThread.join()
.
Passing Arguments to a Thread Function
We can also pass arguments to the thread function when creating a new thread.
#include <iostream>
#include <thread>
void printMessage(const std::string& message) {
std::cout << "Message from thread: " << message << std::endl;
}
int main() {
std::string message = "Hello, C++ Threads!";
std::thread myThread(printMessage, message);
myThread.join();
return 0;
}
Detaching a Thread
Alternatively, we can detach the new thread from the main thread using the detach
method. When a thread is detached, it operates independently, and the main thread does not need to wait for it to finish.
#include <iostream>
#include <thread>
void myFunction() {
std::cout << "Hello from the detached thread!" << std::endl;
}
int main() {
std::thread myThread(myFunction);
// Detach the new thread
myThread.detach();
// The main thread continues to execute without waiting
return 0;
}
Conclusion
The std::thread
class in C++ provides a powerful and flexible way to create multithreaded applications. Whether creating, joining, or detaching threads, it offers a range of options for managing concurrent tasks in C++.
For more information, please refer to the official C++ reference.