代码之家  ›  专栏  ›  技术社区  ›  elmt

在Tcl线程中访问Itcl类作用域

  •  0
  • elmt  · 技术社区  · 14 年前

    首先,这是前一个问题的后续 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 回复  |  直到 7 年前
        1
  •  1
  •   Donal Fellows    14 年前

    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
    
    推荐文章