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.
0 Interaction
152 Views
Views
20 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home