Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Created April 15, 2022 01:56
Show Gist options
  • Save dboyliao/6d802d3ebaa0e4ee96b9b5ff2013dabd to your computer and use it in GitHub Desktop.
Save dboyliao/6d802d3ebaa0e4ee96b9b5ff2013dabd to your computer and use it in GitHub Desktop.
simple threading c++ with callable object
#include <iostream>
#include <thread>
class F {
private:
int data;
public:
F(int data_) : data(data_) {}
F(const F &other) : data(other.data) { std::cout << "copy!" << std::endl; }
F(F &&other) : data(std::move(other.data)) {
std::cout << "move!" << std::endl;
}
F &operator=(const F &other) {
std::cout << "copy assign!" << std::endl;
data = other.data;
return *this;
}
F &operator=(F &&other) {
std::cout << "move assign!" << std::endl;
data = std::move(other.data);
return *this;
}
void operator()() {
std::cout << std::this_thread::get_id() << ": " << data << std::endl;
}
};
int main(int argc, char const *argv[]) {
F f(3);
std::thread t1{f};
// print:
// copy!
// move!
t1.join();
std::thread t2{F(4)};
// print:
// move!
// move!
t2.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment