Tcl Thread: Why this ten lines don't commit in parallel?

53 Views Asked by At
package require Thread

proc multi_thread_job {job_cmds job_thread} {
    set tpool [tpool::create -maxworkers $job_thread]
    set job_idx 1
    set tjobs ""
    foreach job_cmd $job_cmds {
        puts "=== job $job_idx start! ==="
        lappend tjobs [tpool::post -nowait $tpool $job_cmd]
        incr job_idx
    }

    foreach tjob $tjobs {
        tpool::wait $tpool $tjob
    }
    
    tpool::release $tpool
}

set jobs {
    {puts 1;exec sleep 1}
    {puts 2;exec sleep 2}
    {puts 3;exec sleep 3}
    {puts 4;exec sleep 4}
    {puts 5;exec sleep 5}
    {puts 6;exec sleep 6}
    {puts 7;exec sleep 7}
    {puts 8;exec sleep 8}
    {puts 9;exec sleep 9}
    {puts 10;exec sleep 10}
}

multi_thread_job $jobs 5

The ideal result i think should print 1,2,3,4,5 simultaneously and then 6,7,8,9,10 every second... But the result is to print 1,2,3,4,5,6,7,8,9,10 just like serial.

How to fix this Tcl codes to get a parallel version?

2

There are 2 best solutions below

0
Olafur_Z On

I know how to fix it. "tpool::post -nowait" here should be without "-nowait"!!!

I reference this below: https://www.tcl.tk/man/tcl/ThreadCmd/tpool.htm#M10

0
thomas On

-nowait has the effect that tpool::post immediately returns from assigning the task. So this is not the cause of your observation.

You are missing the -minworkers option:

proc multi_thread_job {job_cmds job_thread} {
    set tpool [tpool::create -minworkers $job_thread -maxworkers $job_thread]
    set job_idx 1
    set tjobs ""
    foreach job_cmd $job_cmds {
        puts "=== job $job_idx start! ==="
        lappend tjobs [tpool::post -nowait $tpool $job_cmd]
        incr job_idx
    }

    foreach tjob $tjobs {
        tpool::wait $tpool $tjob
    }
    
    tpool::release $tpool
}

And now 1-5 is printed immediately.