The concurrent execution of numerous threads within a single programme is made possible by C++'s multithreading feature. Particularly in programmes that carry out lengthy or computationally intensive operations, this can result in improved performance and increased efficiency.
The Standard Template Library (STL) threads library, which offers a collection of classes and functions for managing threads, is generally used to implement multithreading in C++. The fundamental stages for developing multithreading in C++ are as follows:
Create a thread object: A thread object in C++ represents a thread. By instantiating the std::thread class and supplying a function or method that should be run in a different thread, you can create a thread object.
Specify the thread's function to be executed: A second thread will be used to perform the function or method that was supplied to the thread object. The code that you wish to run alongside the main thread should be in this method.
Start the thread: You can start the thread by executing the start() method of the thread object after you've created it and specified the function that will be performed in it.
Join the thread: Once the thread has finished its work, you should rejoin it by invoking the join() method of the thread object. This will make sure that the main thread waits until the thread is finished before moving on to the next step of execution.
#include <iostream>
#include <thread>
// Define the function to be executed in the thread
void myThreadFunction(int n) {
for(int i = 0; i < n; i++) {
std::cout << "My Thread executing..." << std::endl;
}
}
int main() {
// Create a thread object and pass the function to be executed in the thread
std::thread myThread(myThreadFunction, 10);
// Wait for the thread to complete
myThread.join();
// Print a message indicating that the thread has completed
std::cout << "MY Thread completed." << std::endl;
return 0;
}
Top comments (0)