Skip to content

Instantly share code, notes, and snippets.

@Shaun289
Created July 18, 2021 06:43
Show Gist options
  • Save Shaun289/9ef794edc85ebeca115d53a0092c00e7 to your computer and use it in GitHub Desktop.
Save Shaun289/9ef794edc85ebeca115d53a0092c00e7 to your computer and use it in GitHub Desktop.
c++ std::thread with class operator
// 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;
}
@Shaun289
Copy link
Author

use std::ref

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment