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

Idiom #30 Parallelize execution of 1000 independent tasks

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.

extern crate rayon;
use rayon::prelude::*;
(0..1000).into_par_iter().for_each(f);
use std::thread;
let threads: Vec<_> = (0..1000).map(|i| {
	thread::spawn(move || f(i))
}).collect();

for thread in threads {
	thread.join();
}
import std.parallelism;
taskPool.amap!f(iota(1, 1001));
lists:foreach(fun(I) -> spawn(?MODULE, _f, [I]) end, lists:seq(1, 1000)).
for i := 1; i <= 1000; i++ {
	go f(i)
}
import Control.Concurrent
mapM_ (forkIO . f) [1..1000]
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

static class RunnableF implements Runnable{
	int i;
	RunnableF(int i){
		this.i=i;
	}
	@Override
	public void run() {
		f(i);
	}
}
ExecutorService executor = Executors.newFixedThreadPool(NB_THREADS);
for (int i = 1; i <= 1000; i++) {
  executor.submit(new RunnableF(i));
}
executor.shutdown();
uses Classes;
type

TThreadF = class(TThread)
  i: Integer;
  constructor Create(const _i: Integer);
  procedure Execute; override;
end;

constructor TThreadF.Create(const _i: Integer);
begin
  i := _i;
  FreeOnTerminate := True;
  inherited Create(False);
end;

procedure TThreadF.Execute;
begin
  f(i);
end;

var i: Integer;

begin
  for i := 1 to 1000 do begin TThreadF.Create(i);
  ReadLn;
end.  
use threads;
for my $i (1 .. 1000) {
    threads->create('f', $i);
}
from multiprocessing import Pool
pool = Pool()
for i in range(1, 1001):
	pool.apply_async(f, [i])
threads = 1000.times.map do |i|
  Thead.new { f(i) }
end
threads.join

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms