
C++ 函数并发编程:创建并管理线程
简介
函数并发编程是一种利用多线程并行执行任务的技术。在 C++ 中,函数并发可以通过创建和管理线程来实现。
创建线程
立即学习“C++免费学习笔记(深入)”;
要创建线程,可以使用 std::thread 类。std::thread 构造函数接受一个可调用对象的引用,该对象指定要执行的任务。例如:
#include void task() { // 执行的任务}int main() { // 创建线程 std::thread t(task); return 0;}
管理线程
一旦创建线程,就可以通过以下方法对其进行管理:
join():等待线程完成。detach():从线程中分离线程对象,以便线程可以独立执行。get_id():获取线程的 ID。
实战案例
下面是一个实战案例,演示如何使用 C++ 函数并发编程计算斐波那契数列:
#include #include #include #include std::vector fibs;void calc_fib(int n) { int a = 0, b = 1; for (int i = 0; i < n; i++) { int next = a + b; fibs.push_back(next); a = b; b = next; }}int main() { int num_threads = 4; int num_fibs_per_thread = 10000000; // 创建线程池 std::vector threads; for (int i = 0; i < num_threads; i++) { threads.emplace_back(std::thread(calc_fib, num_fibs_per_thread)); } // 等待所有线程完成 for (auto& thread : threads) { thread.join(); } // 输出结果 for (auto fib : fibs) { std::cout << fib << " "; } return 0;}
以上就是C++ 函数并发编程:创建并管理线程的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1459266.html
微信扫一扫
支付宝扫一扫