/* 基本类型传值 */ #include <iostream> #include <thread> void func(int num) { num = 100; std::cout << "func: " << num << std::endl; } int main() { int num = 10; std::thread my_job(func, num); my_job.join(); std::cout << "main: " << num << std::endl; return 0; }
/* 基本类型传引用 */ #include <iostream> #include <thread> void func(int &num) { num = 100; std::cout << "func: " << num << std::endl; } int main() { int num = 10; std::thread my_job(func, std::ref(num)); my_job.join(); std::cout << "main: " << num << std::endl; return 0; }
/* 类类型传值 */ #include <iostream> #include <thread> class A { public: int num_; A(int num) : num_(num) { std::cout << "A(int num)" << std::endl; } A(const A &a) : num_(a.num_) { std::cout << "A(const A &a)" << std::endl; } ~A() { std::cout << "~A()" << std::endl; } }; void func(A a) { std::cout << "a.num_ = " << a.num_ << std::endl; a.num_ = 100; } int main() { A a(10); std::thread my_job(func, a); my_job.join(); std::cout << "main : a.num_ = " << a.num_ << std::endl; return 0; }
类类型传值执行结果:多次调用拷贝构造函数,影响效率,所以不推荐这种做法
/* 类类型传引用 */ #include <iostream> #include <thread> class A { public: int num_; A(int num) : num_(num) { std::cout << "A(int num)" << std::endl; } A(const A &a) : num_(a.num_) { std::cout << "A(const A &a)" << std::endl; } ~A() { std::cout << "~A()" << std::endl; } }; void func(A &a) { std::cout << "a.num_ = " << a.num_ << std::endl; a.num_ = 100; } int main() { A a(10); std::thread my_job(func, std::ref(a)); my_job.join(); std::cout << "main : a.num_ = " << a.num_ << std::endl; return 0; }
如果希望子线程里面不修改对象的内容,形参可加const修饰。
/* 传智能指针 */ #include <iostream> #include <thread> void func(std::unique_ptr<int> int_ptr) { std::cout << *int_ptr << std::endl; } int main() { std::unique_ptr<int> int_ptr(new int(10)); std::thread my_job(func, std::move(int_ptr)); my_job.join(); return 0; }