two threads run synchronously

Arjen Markus (11 february 2011) I have been experimenting with the Thread package a bit (after some experiences with OpenMP, MPI and so-called coarrays). The idea is that two (or more threads share the work that is to be done, but they have to keep synchronising among themselves. (The context I am thinking of is the solution or evolution over time of partial differential equations in multiple domains, but that is a mere detail - any iterative process distributing work over several threads might do.)

Here is the code that gets sourced with each thread:

# simple_run.tcl --
#     Library of procedures to be used by simple.tcl

# run --
#     Script to be run by each thread
# Arguments:
#     type       Type of computation
# Returns:
#     Nothing
proc run {type} {

    # First wait for the other thread's ID
    vwait other

    # Now compute, send and wait
    set time 0
    while { $time < 10 } {
        incr time

        if { $type == 1 } {
            set value $time
        } else {
            set value [expr {2 * $time}]

        ::thread::send -async $::other [list set ::other_value $value]

        puts "$type: sent $value"
        vwait other_value
        puts "$type -- $value -- $::other_value"

and here is the code that starts it all:

# simple.tcl --
#     Simply send data back and forth between two threads

package require Thread

# Create the two threads
set id1 [::thread::create -joinable {
        source simple_run.tcl
        run 1
set id2 [::thread::create -joinable {
        source simple_run.tcl
        run 2

::thread::send -async $id1 [list set ::other $id2]
::thread::send -async $id2 [list set ::other $id1]

puts "Waiting ..."
::thread::join $id1
::thread::join $id2