;
; Simple Grid Protocol 1.2 - Copyright (c) Brendan Kosowski 2004, 2005, 2015, 2019
;

(defun sgp-make-thread (anylist &optional (main_thread_id 0))
  (let ((thread_id NIL) (esclist NIL) (rs (make-random-state t)))
    (setq esclist (prin1-to-string anylist))
    (setq thread_id (+ 10000000 (random 90000000 rs)))
    (sb-ext:run-program "/home/grid/os_thread.lisp" (list (write-to-string main_thread_id) (write-to-string thread_id) (format NIL "(prin1 ~a)" esclist)) :search t :wait t :output NIL)
    thread_id
  )
)

(defun sgp-join-threads (threads &optional (main_thread_id 0))
  (let ((poll_delay NIL) (file_name NIL) (flag_complete NIL) (result_list NIL) (fs NIL))
    ; SET THIS: delay in seconds between polling for all threads completed
    (setq poll_delay 0.25)
    (loop
      (sleep poll_delay)
      (setq result_list NIL)
      (setq flag_complete T)
      (loop for thread_id in threads do
        (setq file_name (format NIL "/home/grid/tmp/~a.~a" thread_id main_thread_id))
        ;(if (< (with-open-file (fs file_name) (file-length fs)) 1)
        (setq fs (open file_name :direction :input))
        (if (< (file-length fs) 1)
          (setq flag_complete NIL)
          (push (list (read fs) thread_id) result_list)
        )
        (close fs)
      )
      (if flag_complete
        (return)
      )
    )
    (reverse result_list)
  )
)
