functional multithreaded version