在 tcl 线程中调用 proc
Calling proc within a tcl thread
当我尝试在 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
}
错误信息如下
invalid command name "CPUload"
while executing
"CPUload 1 50000000"
invoked from within
"thread::send $id1 "CPUload 1 50000000""
与许多其他编程语言相比,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"
您可能需要调整代码,以便工作线程在处理完成后将消息发送回原始线程。但是,如何做到这一点超出了您的特定问题的范围。
当我尝试在 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
}
错误信息如下
invalid command name "CPUload" while executing "CPUload 1 50000000" invoked from within "thread::send $id1 "CPUload 1 50000000""
与许多其他编程语言相比,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"
您可能需要调整代码,以便工作线程在处理完成后将消息发送回原始线程。但是,如何做到这一点超出了您的特定问题的范围。