#!/usr/local/bin/sbcl --script

; Calculate pi on 4 best grid machines concurrently (multi thread)

(defvar t0 (get-universal-time))
(setq *print-right-margin* 100000000)
(format t "Calculating pi on 4 best grid machines concurrently (multi thread).~%")
(format t "3.14159265358979323846 is the 20 decimal place target result. Please wait..~%")
(defvar res NIL)
(defvar bigtot 0)
(load "sgp_thread.lisp")

(let ((threads NIL) (main_thread (+ 10000000 (random 90000000 (make-random-state t)))))
  (setq threads (list
    (sgp-make-thread '(progn (load "porta.lisp") (porta '(progn (defvar tot 0)(defvar x 0)
      (dotimes (n 600000)
        (setq x (+ x 2))
        (setq tot (+ tot (round (/ 4000000000000000000000000000000 (* x (+ x 1) (+ x 2))))))
        (setq x (+ x 2))
        (setq tot (- tot (round (/ 4000000000000000000000000000000 (* x (+ x 1) (+ x 2))))))
      ) tot) 0 T)) main_thread)
    (sgp-make-thread '(progn (load "porta.lisp") (porta '(progn (defvar tot 0)(defvar x 2400000)
      (dotimes (n 600000)
        (setq x (+ x 2))
        (setq tot (+ tot (round (/ 4000000000000000000000000000000 (* x (+ x 1) (+ x 2))))))
        (setq x (+ x 2))
        (setq tot (- tot (round (/ 4000000000000000000000000000000 (* x (+ x 1) (+ x 2))))))
      ) tot) 1 T)) main_thread)
    (sgp-make-thread '(progn (load "porta.lisp") (porta '(progn (defvar tot 0)(defvar x 4800000)
      (dotimes (n 600000)
        (setq x (+ x 2))
        (setq tot (+ tot (round (/ 4000000000000000000000000000000 (* x (+ x 1) (+ x 2))))))
        (setq x (+ x 2))
        (setq tot (- tot (round (/ 4000000000000000000000000000000 (* x (+ x 1) (+ x 2))))))
      ) tot) 2 T)) main_thread)
    (sgp-make-thread '(progn (load "porta.lisp") (porta '(progn (defvar tot 0)(defvar x 7200000)
      (dotimes (n 600000)
        (setq x (+ x 2))
        (setq tot (+ tot (round (/ 4000000000000000000000000000000 (* x (+ x 1) (+ x 2))))))
        (setq x (+ x 2))
        (setq tot (- tot (round (/ 4000000000000000000000000000000 (* x (+ x 1) (+ x 2))))))
      ) tot) 3 T)) main_thread)
  ))
  (setq res (sgp-join-threads threads main_thread))
  (format t "~%")
  (format t "Thread results:~%")
  (prin1 res)
  (format t "~%")
  (format t "~%")
)
(setq bigtot (+ (car (car (nth 0 res)))
                (car (car (nth 1 res)))
                (car (car (nth 2 res)))
                (car (car (nth 3 res)))))
(format t "Total:~%")
(format t "~d.~d~%" 3 bigtot)
(defvar t1 (get-universal-time))
(format t "~d seconds~%" (- t1 t0))
