My Blog

My WordPress Blog

My Blog

My WordPress Blog

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 &lt;= limit; ++i) {
        std::cout &lt;&lt; i &lt;&lt; " ";
    }
    std::cout &lt;&lt; std::endl;
}
}; int main() {
Counter counter;
std::thread t(&amp;Counter::countUp, &amp;counter, 5); // Pass the class instance and arguments
t.join(); // Wait for the thread to finish
return 0;
}
Using std::thread with Member Functions

Leave a Reply

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

Scroll to top