在C++中,使用函數對象(也稱為仿函數或functor)進行并發編程時,可以利用多線程庫(如std::thread)來執行多個任務。以下是一個簡單的示例,展示了如何使用函數對象和std::thread實現并發編程:
#include <iostream>
#include <vector>
#include <thread>
// 定義一個簡單的函數對象
struct MyFunctor {
void operator()(int start, int end) const {
for (int i = start; i <= end; ++i) {
std::cout << "Thread ID: " << std::this_thread::get_id() << ", Value: "<< i << std::endl;
}
}
};
int main() {
const int num_threads = 4;
const int range = 100;
// 創建一個包含多個函數對象的向量
std::vector<MyFunctor> functors(num_threads);
// 計算每個線程的工作范圍
int chunk_size = range / num_threads;
// 使用std::thread執行并發任務
std::vector<std::thread> threads;
for (int i = 0; i < num_threads; ++i) {
int start = i * chunk_size + 1;
int end = (i == num_threads - 1) ? range : start + chunk_size - 1;
threads.emplace_back(functors[i], start, end);
}
// 等待所有線程完成
for (auto& t : threads) {
t.join();
}
return 0;
}
在這個示例中,我們定義了一個名為MyFunctor的函數對象,它接受兩個整數參數(開始值和結束值),并在其operator()方法中打印線程ID和值。在main函數中,我們創建了4個線程,并將MyFunctor對象分配給它們。每個線程負責打印一個范圍內的值。最后,我們等待所有線程完成,然后程序退出。
請注意,這個示例僅用于演示目的。在實際應用中,你可能需要考慮線程安全、同步和資源管理等問題。C++11及更高版本提供了std::async和std::packaged_task等高級并發工具,可以簡化并發編程。