Version 0 of Execute in Parallel and Wait

Updated 2014-03-07 06:22:51 by pooryorick

Execute in Parallel and Wait

fileevent is often recommended for execution of multiple processes in parallel, but it requires a script to be written in an event-driven style. Sometimes what is wanted is simple exec-style semantics, but with multiple processes executing in parallel. Here is an example of that:

#! /bin/env tclsh

proc main {} {
    for {set i 0} {$i < 5} {incr i} {
        set command [list | bash -c {
            #busy loop to simulate a hard-working process
            while [[ $((a++)) -lt 1000000 ]]
                do :
            done
            echo done!
        } 2>@stderr]
        set chan [open $command ] 
        dict set res $chan command $command
        fconfigure $chan -blocking 0
        lappend background $chan
    }
    while 1 {
        foreach chan $background {
            if {[eof $chan]} {
                if {[set idx [lsearch -exact $background $chan]] >= 0} {
                    set background [lreplace $background $idx $idx]
                }
                catch [close $chan] cres copts
                dict set res $chan result $cres
                dict set res $chan options $copts
            } else {
                puts -nonewline [read $chan]
            }
        }
        if {[llength $background] == 0} {
            break
        }
        after 100
    }
    return $res
}

#puts [main]
main