c++11特性之std::thread–进阶二

最后更新于:2022-04-01 06:32:13

继续C++11的std::thread之旅! 下面讨论如何**给线程传递参数**  这个例子是传递一个string ~~~ #include <iostream> #include <thread> #include <string> void thread_function(std::string s) { std::cout << "thread function "; std::cout << "message is = " << s << std::endl; } int main() { std::string s = "Kathy Perry"; std::thread t(&thread_function, s); std::cout << "main thread message = " << s << std::endl; t.join(); return 0; } ~~~ 如果运行,我们可以从输出结果看出传递成功了。 良好编程习惯的人都知道 传递引用的效率更高,那么我们该如何做呢?  你也许会这样写: ~~~ void thread_function(std::string &s) { std::cout << "thread function "; std::cout << "message is = " << s << std::endl; s = "Justin Beaver"; } ~~~ 为了确认是否传递了引用?我们在线程函数后更改这个参数,但是我们可以看到,输出结果并没有变化,即不是传递的引用。 事实上, 依然是按值传递而不是引用。为了达到目的,我们可以这么做: ~~~ std::thread t(&thread_function, std::ref(s)); ~~~ 这不是唯一的方法: 我们可以使用move(): ~~~ std::thread t(&thread_function, std::move(s)); ~~~ 接下来呢,我们就要将一下线程的复制吧!!  以下代码编译通过不了: ~~~ #include <iostream> #include <thread> void thread_function() { std::cout << "thread function\n"; } int main() { std::thread t(&thread_function); std::cout << "main thread\n"; std::thread t2 = t; t2.join(); return 0; } ~~~ 但是别着急,稍稍修改: ~~~ include <iostream> #include <thread> void thread_function() { std::cout << "thread function\n"; } int main() { std::thread t(&thread_function); std::cout << "main thread\n"; std::thread t2 = move(t); t2.join(); return 0; } ~~~ 大功告成!!! 再聊一个成员函数吧 **std::thread::get_id()**; ~~~ int main() { std::string s = "Kathy Perry"; std::thread t(&thread_function, std::move(s)); std::cout << "main thread message = " << s << std::endl; std::cout << "main thread id = " << std::this_thread::get_id() << std::endl; std::cout << "child thread id = " << t.get_id() << std::endl; t.join(); return 0; } Output: thread function message is = Kathy Perry main thread message = main thread id = 1208 child thread id = 5224 ~~~ 聊一聊**std::thread::hardware_concurrency()**  获得当前多少个线程: ~~~ int main() { std::cout << "Number of threads = " << std::thread::hardware_concurrency() << std::endl; return 0; } //输出: Number of threads = 2 ~~~ 之前介绍过c++11的**lambda表达式**  我们可以这样使用: ~~~ int main() { std::thread t([]() { std::cout << "thread function\n"; } ); std::cout << "main thread\n"; t.join(); // main thread waits for t to finish return 0; } ~~~
';