fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <functional>
  4. using namespace std;
  5.  
  6. class uart {
  7. public:
  8. void init() { cout<<this<<" is initalized"<<endl; }
  9. void read() { cout<<this<<" is read"<<endl; }
  10. static void static_read(uart& self){ cout<<"static read on "<<&self<<endl;}
  11. };
  12.  
  13. int main() {
  14. uart u;
  15. u.init();
  16. u.read();
  17.  
  18. cout<<"t1"<<endl;
  19. thread t1(uart::static_read, ref(u));
  20. t1.join();
  21.  
  22. cout<<"t2"<<endl;
  23. thread t2([](uart&self){self.read();}, ref(u));
  24. t2.join();
  25.  
  26. cout<<"t3"<<endl;
  27. thread t3(&uart::read, ref(u));
  28. t3.join();
  29.  
  30. cout<<"t4"<<endl;
  31. auto read_my_uart = bind(&uart::read, ref(u)); // without ref it would compile but execute on clone
  32. thread t4(read_my_uart);
  33. t4.join();
  34.  
  35. return 0;
  36. }
Success #stdin #stdout 0s 4520KB
stdin
Standard input is empty
stdout
0x7ffc7c7ac957 is initalized
0x7ffc7c7ac957 is read
t1
static read on 0x7ffc7c7ac957
t2
0x7ffc7c7ac957 is read
t3
0x7ffc7c7ac957 is read
t4
0x7ffc7c7ac957 is read