Tcl变量是每个解释器的变量,解释器强烈绑定到单个线程(这大大减少了所需的全局级锁的数量)。若要执行所需的操作,需要使用共享变量。幸运的是,对它们的支持包含在线程包中(
documentation here
). 然后您可以这样重写代码:
package require Itcl
package require Thread
::itcl::class ThreadTest {
variable thread [thread::create {thread::wait}]
constructor {} {
tsv::set isRunning $this 0
}
method start {} {
tsv::set isRunning $this 1
thread::send $thread {
proc loop {handle} {
puts "thread running"
if { [tsv::get isRunning $handle] } {
after 1000 loop $handle
}
}
}
thread::send $thread [list loop $this]
}
method stop {} {
tsv::set isRunning $this 0
}
}
set t [ThreadTest \#auto]
$t start
vwait forever