Created
July 18, 2021 06:43
-
-
Save Shaun289/9ef794edc85ebeca115d53a0092c00e7 to your computer and use it in GitHub Desktop.
c++ std::thread with class operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reference : https://snowdeer.github.io/c++/2017/08/18/cpp11-thread-example/ | |
// 함수 객체를 이용하는 방법 #2 | |
#include <iostream> | |
#include <thread> | |
#include <chrono> | |
class A | |
{ | |
private: | |
bool running; | |
uint32_t counter; | |
public: | |
A() : running(false), counter(0) {}; | |
void operator() (); | |
void stop() { running = false; }; | |
}; | |
void A::operator() () | |
{ | |
running = true; | |
while (running) { | |
++counter; | |
std::cout << "running count : " << counter << std::endl; | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
} | |
std::cout << "End of thread" << std::endl; | |
} | |
int32_t main(int32_t argc, char* argv[]) | |
{ | |
A a; | |
auto t = std::thread(a); | |
std::this_thread::sleep_for(std::chrono::seconds(3)); | |
a.stop(); | |
t.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
use std::ref