#include#include void hello() { std::cout << "Hello Concurrent Wordn"; } int main() { std::thread t(hello); t.join(); }
这完全就是大材小用了,但这也正是我们开始学习C++并发编程的第一步,如果想要系统的学习C++的多线程并发。
强烈推荐《C++并发编程第二版》,其所使用标准C++111,C++14,C++17,强烈建议对于新标准新特性不了解的诸位,作者更是ios即C++标准委员会的成员之一,书中内容也有多位成员参与编写与帮助。
同时体会多线程并发的魅力。
最简单的发起线程
#include#include void do_some_work(){} class background_task { public: void operator()()const { do_some_work(); } }; int main() { background_task f; std::thread my_thread(f); my_thread.join(); } //函数对象,lambda表达式,函数指针等都可以,这里是使用函数对象
以及利用rall过程等待线程完结,很多很多等待你的学习
#include#include class thread_guard { std::thread& t; public: explicit thread_guard(std::thread& t_) :t(t_) {} ~thread_guard() { if (t.joinable()) { t.join(); } } thread_guard(thread_guard const&) = delete; thread_guard& operator=(thread_guard const&) = delete; }; void do_something() {} struct func { int& i; func(int& i_) :i(i_) {} void operator()() { for (unsigned j = 0; j < 1000000; ++j) { do_something(); } } }; void f() { int some_local_state = 0; func my_func(some_local_state); std::thread t(my_func); thread_guard g(t); do_something(); } int main() { f(); } //20面下半部分到21页
请诸位的编译器要支持C++17



