1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
|
#include <iostream>
#include <future>
#include <vector>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <random>
// 并行计算示例
class ParallelProcessor
{
public:
// 并行求和
static long long parallelSum(const std::vector<int>& data, size_t numThreads = 4)
{
if (data.empty()) return 0;
size_t chunkSize = data.size() / numThreads;
std::vector<std::future<long long>> futures;
for (size_t i = 0; i < numThreads; ++i)
{
size_t start = i * chunkSize;
size_t end = (i == numThreads - 1) ? data.size() : (i + 1) * chunkSize;
futures.push_back(std::async(std::launch::async, [&data, start, end]() {
return std::accumulate(data.begin() + start, data.begin() + end, 0LL);
}));
}
long long total = 0;
for (auto& future : futures)
{
total += future.get();
}
return total;
}
// 并行查找
static std::vector<size_t> parallelFind(const std::vector<int>& data, int target, size_t numThreads = 4)
{
if (data.empty()) return {};
size_t chunkSize = data.size() / numThreads;
std::vector<std::future<std::vector<size_t>>> futures;
for (size_t i = 0; i < numThreads; ++i)
{
size_t start = i * chunkSize;
size_t end = (i == numThreads - 1) ? data.size() : (i + 1) * chunkSize;
futures.push_back(std::async(std::launch::async, [&data, target, start, end]() {
std::vector<size_t> indices;
for (size_t j = start; j < end; ++j)
{
if (data[j] == target)
{
indices.push_back(j);
}
}
return indices;
}));
}
std::vector<size_t> allIndices;
for (auto& future : futures)
{
auto indices = future.get();
allIndices.insert(allIndices.end(), indices.begin(), indices.end());
}
return allIndices;
}
};
// 网络请求模拟
class NetworkClient
{
public:
static std::string simulateHttpRequest(const std::string& url, int delayMs)
{
std::this_thread::sleep_for(std::chrono::milliseconds(delayMs));
return "Response from " + url + " (delay: " + std::to_string(delayMs) + "ms)";
}
static std::vector<std::string> fetchMultipleUrls(const std::vector<std::string>& urls)
{
std::vector<std::future<std::string>> futures;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(100, 1000);
// 启动所有请求
for (const auto& url : urls)
{
int delay = dis(gen);
futures.push_back(std::async(std::launch::async, simulateHttpRequest, url, delay));
}
// 收集所有响应
std::vector<std::string> responses;
for (auto& future : futures)
{
responses.push_back(future.get());
}
return responses;
}
};
// 生产者-消费者模式
class TaskProcessor
{
private:
std::vector<std::function<int()>> m_Tasks;
public:
void addTask(std::function<int()> task)
{
m_Tasks.push_back(task);
}
std::vector<int> processAllTasks()
{
std::vector<std::future<int>> futures;
// 启动所有任务
for (auto& task : m_Tasks)
{
futures.push_back(std::async(std::launch::async, task));
}
// 收集结果
std::vector<int> results;
for (auto& future : futures)
{
results.push_back(future.get());
}
return results;
}
};
void PracticalExamplesDemo()
{
std::cout << "=== Practical Examples Demo ===" << std::endl;
// 1. 并行计算
std::cout << "1. Parallel computation:" << std::endl;
std::vector<int> largeData(1000000);
std::iota(largeData.begin(), largeData.end(), 1); // 填充1到1000000
auto start = std::chrono::high_resolution_clock::now();
long long parallelResult = ParallelProcessor::parallelSum(largeData);
auto end = std::chrono::high_resolution_clock::now();
auto parallelTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
start = std::chrono::high_resolution_clock::now();
long long sequentialResult = std::accumulate(largeData.begin(), largeData.end(), 0LL);
end = std::chrono::high_resolution_clock::now();
auto sequentialTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Parallel result: " << parallelResult << " (time: " << parallelTime.count() << "ms)" << std::endl;
std::cout << "Sequential result: " << sequentialResult << " (time: " << sequentialTime.count() << "ms)" << std::endl;
std::cout << "Results match: " << (parallelResult == sequentialResult ? "Yes" : "No") << std::endl;
// 2. 并行查找
std::cout << "\n2. Parallel search:" << std::endl;
std::vector<int> searchData{1, 5, 3, 5, 7, 5, 9, 5, 2, 5};
auto indices = ParallelProcessor::parallelFind(searchData, 5);
std::cout << "Found value 5 at indices: ";
for (size_t idx : indices)
{
std::cout << idx << " ";
}
std::cout << std::endl;
// 3. 网络请求
std::cout << "\n3. Concurrent network requests:" << std::endl;
std::vector<std::string> urls{
"http://api1.example.com",
"http://api2.example.com",
"http://api3.example.com",
"http://api4.example.com"
};
start = std::chrono::high_resolution_clock::now();
auto responses = NetworkClient::fetchMultipleUrls(urls);
end = std::chrono::high_resolution_clock::now();
auto networkTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Fetched " << responses.size() << " URLs in " << networkTime.count() << "ms:" << std::endl;
for (const auto& response : responses)
{
std::cout << " " << response << std::endl;
}
// 4. 任务处理器
std::cout << "\n4. Task processor:" << std::endl;
TaskProcessor processor;
processor.addTask([]() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
return 10;
});
processor.addTask([]() {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
return 20;
});
processor.addTask([]() {
std::this_thread::sleep_for(std::chrono::milliseconds(150));
return 30;
});
start = std::chrono::high_resolution_clock::now();
auto taskResults = processor.processAllTasks();
end = std::chrono::high_resolution_clock::now();
auto taskTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Processed " << taskResults.size() << " tasks in " << taskTime.count() << "ms:" << std::endl;
for (size_t i = 0; i < taskResults.size(); ++i)
{
std::cout << " Task " << i << " result: " << taskResults[i] << std::endl;
}
}
int main()
{
PracticalExamplesDemo();
return 0;
}
|