在多线程编程中,匿名函数和函数对象可用于创建可调用的代码块,在不创建单独函数的情况下处理并发任务。匿名函数是通过 lambda 表达式定义的,函数对象是通过重载 operator()() 函数实现的类。此类特性使其在并行化任务中十分有用,如所示示例中使用线程并行计算数组元素和的场景。
C++ 匿名函数和函数对象在多线程编程中的作用
前言
在多线程编程中,匿名函数和函数对象在处理并发任务方面发挥着重要的作用。本文将介绍这些概念,展示如何使用它们实现高效的多线程程序。
匿名函数
匿名函数是不具有名称的函数,可以通过 lambda 表达式定义。它们允许在不创建单独函数的情况下创建可调用的代码块。lambda 表达式的语法如下:
[capture-list](parameters) -> return-type { body }
函数对象
函数对象是一种可调用的类,可以通过重载 operator()() 函数实现。与匿名函数不同,函数对象有名称,并且可以复用。
实战案例:多线程求和
以下代码展示了如何在多线程环境中使用匿名函数和函数对象进行求和操作:
#include <iostream> #include <thread> #include <vector> unsigned long long sum = 0; std::vector<std::thread> threads; // 匿名函数求和 void sum_anon(unsigned long long begin, unsigned long long end) { for (unsigned long long i = begin; i < end; ++i) { sum += i; } } // 函数对象求和 class SumFunctor { public: unsigned long long sum = 0; void operator()(unsigned long long begin, unsigned long long end) { for (unsigned long long i = begin; i < end; ++i) { sum += i; } } }; int main() { unsigned long long arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; const int num_threads = 2; const int chunk_size = (sizeof(arr) / sizeof(arr[0])) / num_threads; // 使用匿名函数创建线程 for (int i = 0; i < num_threads; ++i) { threads.push_back(std::thread(sum_anon, i * chunk_size, (i + 1) * chunk_size)); } // 使用函数对象创建线程 SumFunctor sum_functor; for (int i = 0; i < num_threads; ++i) { threads.push_back(std::thread(std::ref(sum_functor), i * chunk_size, (i + 1) * chunk_size)); } // 等待所有线程完成 for (auto &t : threads) { t.join(); } // 计算最终结果 if (num_threads == 1) { // 匿名函数 std::cout << "Sum using anonymous function: " << sum << std::endl; // 函数对象 std::cout << "Sum using function object: " << sum_functor.sum << std::endl; } else { std::cout << "Sum using threads: " << sum << std::endl; } return 0; }
总结
// 这部分已省略,如开头所述