Skip to content

Instantly share code, notes, and snippets.

@sebres
Created March 3, 2020 13:17
Show Gist options
  • Save sebres/fae514b81206c9e050d03f24204d7aa8 to your computer and use it in GitHub Desktop.
Save sebres/fae514b81206c9e050d03f24204d7aa8 to your computer and use it in GitHub Desktop.
threads-communication.tcl -- simplest example how workers can communicate with master
# task params for all threads
tsv::array set params {one 1 two 2}
# worker task:
set th_task {
if {[catch {
# do some work (here sum of params):
set res [expr {[tsv::get params one] + [tsv::get params two]}]
# provide result to master:
thread::send -async $master [list lappend th_res $res]
} msg]} {
puts stderr "worker [thread::id] failed:\n $::errorInfo"
}
}
# main thread:
set th_res {}
foreach i {0 1 2 3} {
set t($i) [thread::create];
# provide a master ID to thread:
thread::send -async $t($i) [list set master [thread::id]]
# send job to threads:
thread::send -async $t($i) $th_task
}
# wait for result from all 4 threads:
while {[llength $th_res] < 4} {
vwait th_res
}
# ready:
puts "results: $th_res"
# release threads:
foreach i {0 1 2 3} {
catch { thread::release -wait $t($i) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment