the code did not worked when data length were more little than number of cpus (6 on my host) (iota 5) returns #unsepcified:
scheme@(guile-user)> (use-modules (ice-9 threads))
scheme@(guile-user)> {v <+ (list->vector (iota 5))}
#(0 1 2 3 4)
scheme@(guile-user)> (par-map-vector sqrt v)
scheme@(guile-user)> {v <+ (list->vector (iota 20))}
#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19)
scheme@(guile-user)> (par-map-vector sqrt v)
#(0 1 1.4142135623730951 1.7320508075688772 2 2.23606797749979 2.449489742783178 2.6457513110645907 2.8284271247461903 3 3.1622776601683795 3.3166247903554 3.4641016151377544 3.605551275463989 3.7416573867739413 3.872983346207417 4 4.123105625617661 4.242640687119285 4.358898943540674)
scheme@(guile-user)> (current-processor-count)
6
scheme@(guile-user)> {v <+ (list->vector (iota 6))}
#(0 1 2 3 4 5)
scheme@(guile-user)> (par-map-vector sqrt v)
#(0 1 1.4142135623730951 1.7320508075688772 2 2.23606797749979)
so i modify it this way:
(define* (par-map-vector proc input
#:optional
(max-thread (current-processor-count)))
(if (< (vector-length input) max-thread)
(list->vector (map proc (vector->list input))) ;; less data than threads or CPUs
(let* ((block-size (quotient (vector-length input) max-thread))
(rest (remainder (vector-length input) max-thread))
(output (make-vector (vector-length input) #f)))
(when (not (zero? block-size))
(let ((mtx (make-mutex))
(cnd (make-condition-variable))
(n 0))
(fold
(lambda (scale output)
(begin-thread
(let lp ((i 0))
(when (< i block-size)
(let ((i (+ i (* scale block-size))))
(vector-set! output i (proc (vector-ref input i))))
(lp (1+ i))))
(with-mutex mtx
(set! n (1+ n))
(signal-condition-variable cnd)))
output)
output
(iota max-thread))
(with-mutex mtx
(while (not (< n max-thread))
(wait-condition-variable cnd mtx))))
(let ((base (- (vector-length input) rest)))
(let lp ((i 0))
(when (< i rest)
(let ((i (+ i base)))
(vector-set! output i (proc (vector-ref input i))))
(lp (1+ i)))))
output))))
now it works but crash randomly, not even at the same stage, i continue to test and debug....