Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #56 Launch 1000 parallel tasks and wait for completion

Fork-join : launch the concurrent execution of procedure f with parameter i from 1 to 1000.
Tasks are independent and f(i) doesn't return any value.
Tasks need not run all at the same time, so you may use a pool.
Wait for the completion of the 1000 tasks and then print "Finished".

use threads;
for my $i (1 .. 1000) {
    threads->create('f', $i);
}
sleep 3 while threads->list(threads::running);
print "Finished\n";

# optional: threads library wants you to explicitly join or detach
# your threads before exiting program.
$_->join() for threads->list(threads::joinable);

If you don't use the optional line, you'll get a warning about threads not joined/detached when your program stops.
#include<latch>
#include<thread>
size_t taskCount = 1000;
auto remainingTasks = std::latch(static_cast<std::ptrdiff_t>(taskCount));
auto f = [&remainingTasks](int i) {
  // do work
  remainingTasks.count_down();
};

std::vector<std::jthread> threads{ 10 };
for (auto i = 0; i < taskCount; i++) {
  auto& workerThread = threads[i % 10];
  if (workerThread.joinable()) {
    workerThread.join();
  }
  workerThread = std::jthread(f, i);
}

remainingTasks.wait();
std::cout << "Finished";

Latch is used to wait until all tasks are completed. Simulated thread pool with vector of jthreads.

New implementation...