#include <thread>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
constexpr int kTopThreads = 20;
constexpr int kChildThreads = 30;
constexpr int kChildIterations = REUSE ? 8 : 1;
constexpr int kProcessIterations = 20;
void Thread() {
for (int i = 0; i < kChildIterations; ++i) {
std::vector<std::thread> threads;
threads.reserve(kChildThreads);
for (int i = 0; i < kChildThreads; ++i)
threads.emplace_back([]() {});
for (auto &t : threads)
t.join();
}
}
void run() {
std::vector<std::thread> threads;
threads.reserve(kTopThreads);
for (int i = 0; i < kTopThreads; ++i)
threads.emplace_back(Thread);
for (auto &t : threads)
t.join();
}
int main() {
#if REUSE
run();
#else
for (int i = 0; i < kProcessIterations; ++i) {
int pid = fork();
if (pid) {
int wstatus;
do {
waitpid(pid, &wstatus, 0);
} while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus));
if (!WIFEXITED(wstatus) || WEXITSTATUS(wstatus)) {
fprintf(stderr, "failed at iteration %d / %d\n", i, kProcessIterations);
return 1;
}
} else {
run();
return 0;
}
}
#endif
}