Using std::thread with Member Functions

This example demonstrates how to create threads that run member functions of a class.

cppCopy code#include <iostream>
#include <thread>

class Counter {
public:
    void countUp(int limit) {
        for (int i = 1; i <= limit; ++i) {
            std::cout << i << " ";
        }
        std::cout << std::endl;
    }
};

int main() {
    Counter counter;
    std::thread t(&Counter::countUp, &counter, 5); // Pass the class instance and arguments
    t.join(); // Wait for the thread to finish
    return 0;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *