Created
April 15, 2022 01:56
-
-
Save dboyliao/6d802d3ebaa0e4ee96b9b5ff2013dabd to your computer and use it in GitHub Desktop.
simple threading c++ with callable object
This file contains 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
#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