-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParallelKitNET.cpp
More file actions
88 lines (70 loc) · 2.09 KB
/
ParallelKitNET.cpp
File metadata and controls
88 lines (70 loc) · 2.09 KB
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
#include "ParallelKitNET.h"
#include <iostream>
// 大部分实现已经在头文件中完成,这里主要提供一些额外的辅助函数
// 示例:一个帮助函数,直接返回处理结果而不是future
double ParallelKitNET::processAndWait(const std::vector<double> &x) {
auto future = process(x, false);
return future.get();
}
// 示例:一个帮助函数,直接返回训练结果而不是future
double ParallelKitNET::trainAndWait(const std::vector<double> &x) {
auto future = train(x, false);
return future.get();
}
// 批量处理一组特征向量,并等待所有结果
std::vector<double>
ParallelKitNET::batchProcess(const std::vector<std::vector<double>> &batch,
bool block) {
std::vector<std::future<double>> futures;
futures.reserve(batch.size());
// 提交所有工作项
for (const auto &x : batch) {
futures.push_back(process(x, false));
}
// 如果不阻塞,直接返回空结果
if (!block) {
return {};
}
// 收集所有结果
std::vector<double> results;
results.reserve(batch.size());
for (auto &future : futures) {
results.push_back(future.get());
}
return results;
}
// 批量训练一组特征向量,并等待所有结果
std::vector<double>
ParallelKitNET::batchTrain(const std::vector<std::vector<double>> &batch,
bool block) {
std::vector<std::future<double>> futures;
futures.reserve(batch.size());
// 提交所有工作项
for (const auto &x : batch) {
futures.push_back(train(x, false));
}
// 如果不阻塞,直接返回空结果
if (!block) {
return {};
}
// 收集所有结果
std::vector<double> results;
results.reserve(batch.size());
for (auto &future : futures) {
results.push_back(future.get());
}
return results;
}
// 调整工作线程数量
void ParallelKitNET::resizeThreadPool(size_t num_threads) {
// 停止当前所有线程
stopThreads();
// 启动新的线程池
startThreads(num_threads);
}
// 等待所有当前队列中的任务完成
void ParallelKitNET::waitForAllTasks() {
while (!workQueue.empty() && running) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}