diff --git a/examples/07_Threads.mers b/examples/07_Threads.mers new file mode 100644 index 0000000..26da3e2 --- /dev/null +++ b/examples/07_Threads.mers @@ -0,0 +1,33 @@ +is_prime := n -> { + 0.1.sleep // wow, what an inefficient algorithm, oh no + d := 1 + ().loop(() -> { + &d = (d, 1).sum + if d.lt(n) { + if n.modulo(d).eq(0) (false) + } else (true) + }) +} + +find_primes := start_at -> { + () -> (().loop(() -> { + out := if start_at.is_prime (start_at) + &start_at = (start_at, 1).sum + out + })) +} + +primes_count := 0 + +background_thread := {() -> + 2.find_primes.take(20).map(p -> { &primes_count = (primes_count, 1).sum, p }).as_list +}.thread + +// Show status to the user while the background thread works +().loop(() -> { + 0.2.sleep + (" Found ", primes_count, " primes...\r").concat.print + if background_thread.thread_finished (()) +}) + +("\nPrimes: ", background_thread.thread_await).concat.println