๐งต Multithreading in C++ – Basics Using std::thread
C++11 introduced the <thread>
library that provides a simple and efficient way to implement multithreading. This allows multiple parts of a program to run concurrently, improving performance in tasks such as file I/O, network operations, and complex computations.
๐ What is Multithreading?
Multithreading is the concurrent execution of two or more threads (independent paths of execution) within a program. It enables you to divide tasks and run them in parallel to optimize CPU usage.
๐ง Key Concepts
- Thread Creation: Using
std::thread
with a function. - Join: Wait for the thread to finish.
- Detach: Run independently without blocking main thread.
๐ป Example: Simple Multithreading with std::thread
#include <iostream>
#include <thread>
using namespace std;
// Function to be run on a separate thread
void printMessage(string msg, int times) {
for (int i = 0; i < times; ++i) {
cout << msg << " (" << i + 1 << ")" << endl;
}
}
int main() {
// Create a thread and run printMessage
thread t1(printMessage, "Thread 1 running", 3);
// Main thread work
for (int i = 0; i < 3; ++i) {
cout << "Main thread work (" << i + 1 << ")" << endl;
}
// Wait for t1 to complete
t1.join();
return 0;
}
๐ Sample Output
Thread 1 running (1)
Main thread work (1)
Thread 1 running (2)
Main thread work (2)
Thread 1 running (3)
Main thread work (3)
Main thread work (1)
Thread 1 running (2)
Main thread work (2)
Thread 1 running (3)
Main thread work (3)
๐ Explanation
printMessage
runs in a new thread created usingstd::thread
.t1.join()
ensures the main function waits until the thread finishes.- Threads may interleave outputs depending on CPU scheduling.
๐ Tips
- Always join or detach your threads to avoid runtime errors.
- Use
std::mutex
to manage shared resources (not shown here). - Thread execution order is not guaranteed.
Post a Comment