首先,这是之前关于mine的一个问题的后续。
我想在Tcl中使用线程,但要与Itcl协作。
下面是一个示例:
package require Itcl
package require Thread
::itcl::class ThreadTest {
variable thread [thread::create {thread::wait}]
variable isRunning 0
method start {} {
set isRunning 1
thread::send $thread {
proc loop {} {
puts "thread running"
if { $isRunning } {
after 1000 loop
}
}
loop
}
}
method stop {} {
set isRunning 0
}
}
set t [ThreadTest \#auto]
$t start
vwait forever但是,当条件语句尝试执行并检查isRunning变量是否为true时,我得到一个没有这样的变量的错误。我知道这是因为proc只能访问全局作用域。但是,在这种情况下,我希望包含类的本地变量。
有没有办法做到这一点?
发布于 2010-12-01 19:53:25
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 foreverhttps://stackoverflow.com/questions/4305957
复制相似问题