(bind-func main
(let ((num_elements_per_proc:i32 1000))
(lambda ()
(MPI_Init null null)
(let ((world_size_ptr:i32* (salloc))
(world_size (begin
(MPI_Comm_size MPI_COMM_WORLD world_size_ptr)
(pref world_size_ptr 0)))
(world_rank_ptr:i32* (salloc))
(world_rank (begin
(MPI_Comm_rank MPI_COMM_WORLD world_rank_ptr)
(pref world_rank_ptr 0)))
(number:i32* (salloc)))
(letz ((rand_nums:float* (zalloc num_elements_per_proc))
(local_sum 0.0)
(global_sum_ptr:float* (salloc))
(i 0))
;; Create a random array of elements on all processes.
(dotimes (i num_elements_per_proc)
(pset! rand_nums i (random)))
;; Sum the numbers locally
(dotimes (i num_elements_per_proc)
(set! local_sum (+ local_sum (pref rand_nums i))))
;; Print the random numbers on each process
(printf "Local sum for process %d: %f, avg = %f\n"
world_rank (convert local_sum double) (/ (convert local_sum double) (convert num_elements_per_proc double)));
;; Reduce all of the local sums into the global sum
(MPI_Reduce (let ((ptr:float* (salloc)))
(pset! ptr 0 local_sum)
(convert ptr i8*))
(convert global_sum_ptr i8*)
1 MPI_FLOAT MPI_SUM 0 MPI_COMM_WORLD)
;; Print the result
(if (= world_rank 0)
(printf "Total sum = %f, avg = %f\n"
(convert (pref global_sum_ptr 0) double) (convert (/ (pref global_sum_ptr 0) (convert (* world_size num_elements_per_proc))) double)))
(MPI_Barrier MPI_COMM_WORLD)
(MPI_Finalize))))))