【问题标题】:Calling proc within a tcl thread在 tcl 线程中调用 proc
【发布时间】:2015-08-22 05:52:20
【问题描述】:

当我尝试在 tcl 线程中调用 proc 时,我收到一个错误,指出命令名称无效。以下是我的 tcl 代码。请帮助确定为什么在线程中无法识别 proc。谢谢。

package require Thread

proc CPUload { Start Stop } {
    for {set i $Start} {$i <= $Stop} {incr i} { 
        set j [expr {sqrt($i)*sqrt($i)}] 
        set k [expr {$i % 123}] 
    } 
}

set id1 [thread::create]

catch {thread::send $id1 "CPUload 1 50000000"} ret

puts $ret
puts $errorInfo

while {[llength [thread::names]] > 1} {
    after 500
}

错误信息如下

无效的命令名称“CPUload” 在执行时 “CPU负载 1 50000000” 从内部调用 "thread::send $id1 "CPUload 1 50000000""

【问题讨论】:

  • 阅读线程文档...您需要在线程中加载/初始化您的 proc,它们不会自动/神奇地共享。

标签: multithreading tcl proc


【解决方案1】:

与许多其他编程语言相比,Tcl 线程之间的独立性要强得多。每个都有自己的解释器,一个完全不同的上下文,有自己的命令(和过程)和“全局”变量。您需要在另一个线程中创建您的程序。

然而,事实证明这很简单。

set id1 [thread::create]
thread::send $id1 {
    proc CPUload { Start Stop } {
        for {set i $Start} {$i <= $Stop} {incr i} { 
            set j [expr {sqrt($i)*sqrt($i)}] 
            set k [expr {$i % 123}] 
        } 
    }
}

您可能还想对重载调用使用-async 选项,这样您就不会挂起原始线程等待事情完成。

thread::send -async $id1 "CPUload 1 50000000"

您可能需要调整代码,以便工作线程在处理完成后将消息发送回原始线程。但是,如何做到这一点超出了您的特定问题的范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多