Skip to content

Commit

Permalink
refactor(learn): 并行执行时使用一个线程池
Browse files Browse the repository at this point in the history
Signed-off-by: YdrMaster <[email protected]>
  • Loading branch information
YdrMaster committed Jul 20, 2024
1 parent ac3dc00 commit 38f836c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
4 changes: 2 additions & 2 deletions exercises/19_runtime_datatype/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ int main(int argc, char **argv) {
xf.f = 5.f;
auto yf = sigmoid_dyn(xf);
ASSERT(yf.type == DataType::Float, "type mismatch");
ASSERT(yf.f == 1 / (1 + exp(-5.f)), "sigmoid float");
ASSERT(yf.f == 1 / (1 + std::exp(-5.f)), "sigmoid float");

TaggedUnion xd{DataType::Double};
xd.d = 5.0;
auto yd = sigmoid_dyn(xd);
ASSERT(yd.type == DataType::Double, "type mismatch");
ASSERT(yd.d == 1 / (1 + exp(-5.0)), "sigmoid double");
ASSERT(yd.d == 1 / (1 + std::exp(-5.0)), "sigmoid double");
return 0;
}
26 changes: 21 additions & 5 deletions learn/summary.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "test.h"
#include <atomic>
#include <chrono>
#include <cstring>
#include <iomanip>
Expand All @@ -24,14 +25,29 @@ int main(int argc, char **argv) {
return EXIT_SUCCESS;
}
if (argc == 2 && std::strcmp(argv[1], "--simple") == 0) {
Log log{Null{}};
auto concurrency = std::thread::hardware_concurrency();
if (concurrency == 0) {
concurrency = 1;
}

std::atomic_int k{0};
std::vector<std::thread> threads;
for (auto i = 0; i <= MAX_EXERCISE; ++i) {
threads.emplace_back([&log, i]() { log << i; });
threads.reserve(concurrency);

Log log{Null{}};
for (auto i = 0u; i <= concurrency; ++i) {
threads.emplace_back([&log, &k] {
int i = k.fetch_add(1);
while (i <= MAX_EXERCISE) {
log << i;
i = k.fetch_add(1);
}
});
}
for (auto i = 0; i <= MAX_EXERCISE; ++i) {
threads[i].join();
for (auto &thread : threads) {
thread.join();
}

std::cout << std::accumulate(log.result.begin(), log.result.end(), 0, std::plus{}) << '/' << MAX_EXERCISE + 1 << std::endl;
return EXIT_SUCCESS;
}
Expand Down
Empty file removed log/placeholder
Empty file.

0 comments on commit 38f836c

Please sign in to comment.