RosettaCodeData/Task/Parallel-calculations/Phix/parallel-calculations.phix

44 lines
1.1 KiB
Plaintext

-- demo/rosetta/ParallelCalculations.exw
include mpfr.e
sequence res
constant res_cs = init_cs() -- critical section
procedure athread()
mpz z = mpz_init()
while true do
integer found = 0
enter_cs(res_cs)
for i=1 to length(res) do
if integer(res[i]) then
found = i
res[i] = {}
exit
end if
end for
leave_cs(res_cs)
if not found then exit end if
mpz_ui_pow_ui(z,2,found)
mpz_add_ui(z,z,1)
sequence r = mpz_prime_factors(z, 1_000_000)
enter_cs(res_cs)
res[found] = r
leave_cs(res_cs)
end while
exit_thread(0)
end procedure
for nthreads=1 to 5 do
atom t0 = time()
res = tagset(100)
sequence threads = {}
for i=1 to nthreads do
threads = append(threads,create_thread(routine_id("athread"),{}))
end for
wait_thread(threads)
integer k = largest(res,true)
string e = elapsed(time()-t0)
printf(1,"largest is 2^%d+1 with smallest factor of %d (%d threads, %s)\n",
{k,res[k][1][1],nthreads,e})
end for
delete_cs(res_cs)