Skip to content

Commit 38f836c

Browse files
committed
refactor(learn): 并行执行时使用一个线程池
Signed-off-by: YdrMaster <[email protected]>
1 parent ac3dc00 commit 38f836c

File tree

3 files changed

+23
-7
lines changed

3 files changed

+23
-7
lines changed

exercises/19_runtime_datatype/main.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@ int main(int argc, char **argv) {
3434
xf.f = 5.f;
3535
auto yf = sigmoid_dyn(xf);
3636
ASSERT(yf.type == DataType::Float, "type mismatch");
37-
ASSERT(yf.f == 1 / (1 + exp(-5.f)), "sigmoid float");
37+
ASSERT(yf.f == 1 / (1 + std::exp(-5.f)), "sigmoid float");
3838

3939
TaggedUnion xd{DataType::Double};
4040
xd.d = 5.0;
4141
auto yd = sigmoid_dyn(xd);
4242
ASSERT(yd.type == DataType::Double, "type mismatch");
43-
ASSERT(yd.d == 1 / (1 + exp(-5.0)), "sigmoid double");
43+
ASSERT(yd.d == 1 / (1 + std::exp(-5.0)), "sigmoid double");
4444
return 0;
4545
}

learn/summary.cpp

+21-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "test.h"
2+
#include <atomic>
23
#include <chrono>
34
#include <cstring>
45
#include <iomanip>
@@ -24,14 +25,29 @@ int main(int argc, char **argv) {
2425
return EXIT_SUCCESS;
2526
}
2627
if (argc == 2 && std::strcmp(argv[1], "--simple") == 0) {
27-
Log log{Null{}};
28+
auto concurrency = std::thread::hardware_concurrency();
29+
if (concurrency == 0) {
30+
concurrency = 1;
31+
}
32+
33+
std::atomic_int k{0};
2834
std::vector<std::thread> threads;
29-
for (auto i = 0; i <= MAX_EXERCISE; ++i) {
30-
threads.emplace_back([&log, i]() { log << i; });
35+
threads.reserve(concurrency);
36+
37+
Log log{Null{}};
38+
for (auto i = 0u; i <= concurrency; ++i) {
39+
threads.emplace_back([&log, &k] {
40+
int i = k.fetch_add(1);
41+
while (i <= MAX_EXERCISE) {
42+
log << i;
43+
i = k.fetch_add(1);
44+
}
45+
});
3146
}
32-
for (auto i = 0; i <= MAX_EXERCISE; ++i) {
33-
threads[i].join();
47+
for (auto &thread : threads) {
48+
thread.join();
3449
}
50+
3551
std::cout << std::accumulate(log.result.begin(), log.result.end(), 0, std::plus{}) << '/' << MAX_EXERCISE + 1 << std::endl;
3652
return EXIT_SUCCESS;
3753
}

log/placeholder

Whitespace-only changes.

0 commit comments

Comments
 (0)