This tutorial aims to introduce you to the concept of multithreading in C++. You'll learn what threads are, how they work, and why they are used in programming. By the end of this tutorial, you should be able to write, understand, and analyze multithreaded programs in C++.
You will learn
Prerequisites
Threads are the smallest sequences of programmed instructions that can be managed independently by a scheduler. Multithreading is the ability of a processor to execute multiple threads concurrently. In C++, you can use the <thread>
library to create and manage threads.
In C++, you can create a thread by creating an object of the std::thread
class and passing a function to the constructor.
#include <iostream>
#include <thread>
void printHello() {
std::cout << "Hello, World!" << std::endl;
}
int main() {
std::thread threadObj(printHello);
threadObj.join();
return 0;
}
The threadObj.join()
line ensures that the main thread waits for threadObj
to finish execution before it continues.
#include <iostream>
#include <thread>
// Function to be executed by thread
void function_1() {
std::cout << "Function 1 has been called!" << std::endl;
}
int main() {
// Creating a thread that executes function_1
std::thread t1(function_1);
// Wait for t1 to finish
t1.join();
std::cout << "Main function has finished execution" << std::endl;
return 0;
}
Output
Function 1 has been called!
Main function has finished execution
#include <iostream>
#include <thread>
// Function to calculate the sum of two numbers
void function_2(int num1, int num2) {
std::cout << "The sum is: " << num1 + num2 << std::endl;
}
int main() {
std::thread t2(function_2, 10, 20);
t2.join();
return 0;
}
Output
The sum is: 30
std::thread
class in the <thread>
library.join()
function allows the main thread to wait for the other threads to finish their execution.Next, you could learn about more advanced topics like thread synchronization, thread pools, and thread safety. Some additional resources include the <thread>
library documentation and C++ Concurrency in Action by Anthony Williams.
Exercise 1: Write a program that creates a separate thread to print numbers from 1 to 10.
Exercise 2: Write a program that creates two threads. One thread prints all even numbers from 1 to 20, and the other thread prints all odd numbers.
Exercise 3: Write a program where multiple threads calculate the factorial of a number, and the main thread prints the result.
Exercise Solutions
#include <iostream>
#include <thread>
void printNumbers() {
for(int i = 1; i <= 10; i++) {
std::cout << i << std::endl;
}
}
int main() {
std::thread t(printNumbers);
t.join();
return 0;
}
Remember, practice is key to mastering multithreading. Try to come up with and solve more complex problems to improve your understanding. Happy coding!