thread


Header: <thread>

The <thread> header, introduced in C++11, provides a standardized way to create and manage threads in C++. It allows for concurrent execution of code, enabling developers to write multi-threaded applications that can take advantage of modern multi-core processors.

Key Characteristics

Example 1: Basic Thread Creation and Joining

#include <iostream>
#include <thread>

void print_numbers(int id) {
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread " << id << ": " << i << std::endl;
    }
}

int main() {
    std::thread t1(print_numbers, 1);
    std::thread t2(print_numbers, 2);

    t1.join();
    t2.join();

    std::cout << "All threads completed." << std::endl;
    return 0;
}

Explanation

Example 2: Using Lambda Expressions with Threads

#include <iostream>
#include <thread>
#include <vector>

int main() {
    std::vector<std::thread> threads;

    for (int i = 0; i < 3; ++i) {
        threads.emplace_back([i]() {
            std::cout << "Thread " << i << " is running." << std::endl;
        });
    }

    for (auto& t : threads) {
        t.join();
    }

    std::cout << "All threads completed." << std::endl;
    return 0;
}

Explanation

Example 3: Sharing Data Between Threads

#include <iostream>
#include <thread>
#include <mutex>

int shared_value = 0;
std::mutex mtx;

void increment(int id) {
    for (int i = 0; i < 1000; ++i) {
        std::lock_guard<std::mutex> lock(mtx);
        ++shared_value;
        std::cout << "Thread " << id << " incremented value to " << shared_value << std::endl;
    }
}

int main() {
    std::thread t1(increment, 1);
    std::thread t2(increment, 2);

    t1.join();
    t2.join();

    std::cout << "Final value: " << shared_value << std::endl;
    return 0;
}

Explanation

Example 4: Using std::async for Asynchronous Tasks

#include <iostream>
#include <future>
#include <chrono>

int compute_value() {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 42;
}

int main() {
    std::cout << "Starting async operation..." << std::endl;

    std::future<int> result = std::async(std::launch::async, compute_value);

    std::cout << "Doing other work..." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));

    std::cout << "Result is: " << result.get() << std::endl;

    return 0;
}

Explanation

Additional Considerations

Summary

The <thread> header in C++ provides a powerful and flexible way to implement concurrent programming. It offers tools for creating and managing threads, synchronizing their execution, and sharing data between them.

Key points to remember:

  1. Use std::thread to create new threads of execution
  2. Always either join() or detach() a thread before it's destroyed
  3. Use synchronization primitives like mutexes to protect shared data
  4. Consider using std::async for simple asynchronous tasks
  5. Be mindful of potential issues like data races and deadlocks in multi-threaded code

By effectively using the features provided by <thread>, C++ developers can create efficient, concurrent applications that take full advantage of modern multi-core processors. However, it's crucial to understand the complexities and potential pitfalls of multi-threaded programming to ensure correct and efficient implementations.

Citations:

[1] https://stackoverflow.com/questions/45105447/creating-stdthread-in-class-with-header [2] https://www.youtube.com/watch?v=zUy66Bats5c [3] https://en.cppreference.com/w/cpp/thread/thread [4] https://www.geeksforgeeks.org/multithreading-in-cpp/ [5] https://stackoverflow.com/questions/660621/threading-best-practices [6] https://en.cppreference.com/w/cpp/header/thread [7] https://www.geeksforgeeks.org/introduction-to-c-programming-language/ [8] https://cplusplus.com/reference/thread/thread/

Previous Page | Course Schedule | Course Content