set arg1 [lindex $::argv 0]

interp create code1
interp create code2


puts stderr "loading Thread package in all 3 interps"
package require Thread
code1 eval {package require Thread}
code2 eval {package require Thread}

puts stderr "establishing ::testfunc proc in all 3 interps"
code1 eval {proc ::testfunc {args}  {puts stderr "evaluated in code1  interp: $args"}}
code2 eval {proc ::testfunc {args}  {puts stderr "evaluated in code2  interp: $args"}}
proc ::testfunc {args}              {puts stderr "evaluated in parent interp: $args"}


puts stderr "Calling a thread function in nominated interp '$arg1' first"
#1st use of thread function makes that interp the one to receive all subsequent messages
switch -- $arg1 {
    parent {
        thread::id
    }
    code1 {
        code1 eval {thread::id}
    }
    code2 {
        code2 eval {thread::id}
    }
    default {
        puts stderr "Usage thread_interp.tcl parent|code1|code2"
        exit 1
    }
}


puts stderr "sending scripts"
thread::send -async [thread::id] {
    ::testfunc script sent from parent interp
}
code1 eval {
    thread::send -async [thread::id] {
        ::testfunc script sent from code1 interp
    }
}
code2 eval {
    thread::send -async [thread::id] {
        ::testfunc script sent from code2 interp
    }
}
#test
after 0                 {::testfunc after script in parent interp}
code1 eval  {after 0    {::testfunc after script in code1 interp}}
code2 eval  {after 0    {::testfunc after script in code2 interp}}


code1 eval {
    set workertid [thread::create]
    thread::send $workertid {package require Thread}
    thread::send $workertid [list thread::send -async [thread::id] {
            ::testfunc script sent from code1 interp via worker
    }]
}

after idle {set ::done 1}
vwait ::done