访问Tcl线程中的Itcl类范围

时间:2010-11-29 16:50:45

标签: multithreading tcl scope incr-tcl

首先,这是对前一个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变量是否为真时,我得到一个没有这样的变量错误。我理解这是因为proc只能访问全局范围。但是,在这种情况下,我想在类中包含本地变量。

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

Tcl变量是每个解释器,并且解释器强烈绑定到单个线程(这大大减少了所需的全局级锁的数量)。要做你想做的事,你需要使用共享变量。幸运的是,Thread包中包含了对它们的支持(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
相关问题