C++ Multithreading Tutorial
Multithreading in C++ allows concurrent execution of multiple threads, which can improve the efficiency of programs by leveraging multiple CPU cores.
Basic Thread Creation
Use the std::thread library to create threads:
#include <thread>
#include <iostream>
using namespace std;
void printMessage() {
cout << "Hello from thread!" << endl;
}
int main() {
thread t1(printMessage);
t1.join(); // Wait for the thread to finish
return 0;
}
Thread Arguments
Pass arguments to threads using functions or lambdas:
#include <thread>
#include <iostream>
using namespace std;
void printNumber(int n) {
cout << "Number: " << n << endl;
}
int main() {
thread t2(printNumber, 42);
t2.join();
return 0;
}
Synchronization
Use synchronization tools like mutexes to avoid data races:
#include <thread>
#include <mutex>
#include <iostream>
using namespace std;
mutex mtx;
void printSafe(int n) {
lock_guard<mutex> lock(mtx);
cout << "Thread-safe number: " << n << endl;
}
int main() {
thread t3(printSafe, 1);
thread t4(printSafe, 2);
t3.join();
t4.join();
return 0;
}
Advantages of Multithreading
- Improves performance by parallelizing tasks.
- Optimizes CPU usage, especially on multi-core systems.
- Enhances responsiveness in applications.
×