Multithreading in C++ | std::thread Basics with Example

Multithreading in C++ | std::thread Basics with Example

๐Ÿงต 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)

๐Ÿ” Explanation

  • printMessage runs in a new thread created using std::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

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences