2010-11-29 19 views
0

首先,這是前一個問題mine的後續操作。在Tcl中訪問Itcl類作用域線程

我想在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

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 
+0

請注意,您需要將對象句柄'$ this`傳遞給另一個線程,以便知道發生了什麼。使用`list`來構建該消息是最簡單的方法,但它只能構建單個命令。 – 2010-12-01 11:55:22