C++程序中启动线程的方法
C++11 引入一个全新的线程库,包含启动和管理线程的工具,提供了同步(互斥、锁和原子变量)的方法,我将试图为你介绍这个全新的线程库。 如果你要编译本文中的代码,你至少需要一个支持 C++11 的编译器,我使用的是 GCC 4.6.1,需要使用 -c++0x 或者 -c++11 参数来启用 C++11 的支持。 启动线程 在 C++11 中启动一个线程是非常简单的,你可以使用 std:thread 来创建一个线程实例,创建完会自动启动,只需要给它传递一个要执行函数的指针即可,请看下面这个 Hello world 代码: #include <thread> #include <iostream> void hello(){ std::cout << "Hello from thread " << std::endl; } int main(){ std::thread t1(hello); t1.join(); return 0; }
线程标识 每个线程都有一个唯一的 ID 以识别不同的线程,std:thread 类有一个 get_id() 方法返回对应线程的唯一编号,你可以通过 std::this_thread 来访问当前线程实例,下面的例子演示如何使用这个 id: #include <thread> #include <iostream> #include <vector> void hello(){ std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; } int main(){ std::vector<std::thread> threads; for(int i = 0; i < 5; ++i){ threads.push_back(std::thread(hello)); } for(auto& thread : threads){ thread.join(); } return 0; }
Hello from thread 140276650997504 Hello from thread 140276667782912 Hello from thread 140276659390208 Hello from thread 140276642604800 Hello from thread 140276676175616 也可能是: Hello from thread Hello from thread Hello from thread 139810974787328Hello from thread 139810983180032Hello from thread 139810966394624 139810991572736 139810958001920 或者其他结果,因为多个线程的执行是交错的。你完全没有办法去控制线程的执行顺序(否则那还要线程干吗?)
#include <thread> #include <iostream> #include <vector> int main(){ std::vector<std::thread> threads; for(int i = 0; i < 5; ++i){ threads.push_back(std::thread([](){ std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; })); } for(auto& thread : threads){ thread.join(); } return 0; } 在这里我们使用了一个 lambda 表达式替换函数指针,而结果是一样的。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |