今天开始总结一下c++并发编程的内容。首先我们看一下 如何启动一个线程以及如何像线程传递参数等。
直接看代码:
启动线程
1 2 3 4 5 6 7 8 9 10 11 12
| #include <iostream> #include <thread>
void hello() { std::cout << "hello cpp concurrency !" << std::endl; } int main(int argc, const char * argv[]) { std::thread my_thread(hello); my_thread.join(); return 0; }
|
这里要注意 join()
的用法,是为了防止 main函数所在线程退出,等待运行 hello的线程结束。与之对应的函数为 detach
,分离线程,不等待。
像线程传递参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <iostream> #include <thread>
void hello(std::string& str) { str = "123"; }
int main(int argc, const char * argv[]) { std::string s("abc"); std::thread my_thread(hello, std::ref(s)); my_thread.join(); std::cout << s << std::endl; return 0; }
class X { public: void do_lengthy_work(); }; X my_x; std::thread t(&X::do_lengthy_work,&my_x);
|
转移线程所有权
运行时决定线程数量
识别线程