问题
When I try to call a proc within a tcl thread, I get an error stating invalid command name. Following is my tcl code. Pls help in identifying why the proc is not recognized within the thread. Thanks.
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
}
Error msg is as follows
invalid command name "CPUload" while executing "CPUload 1 50000000" invoked from within "thread::send $id1 "CPUload 1 50000000""
回答1:
Tcl threads are much more strongly independent from each other than in many other programming languages. Each has its own interpreter, a totally different context with its own commands (and procedures) and “global” variables. You need to create your procedures in the other thread.
However, it turns out to be pretty simple.
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}]
}
}
}
You also probably want to use the -async
option to the heavy load call so that you don't suspend the origin thread waiting for things to finish.
thread::send -async $id1 "CPUload 1 50000000"
You may want to adjust your code so that the worker thread sends a message back to the origin thread when the processing is done. How to do that is out of the scope of your particular question though.
来源:https://stackoverflow.com/questions/32152842/calling-proc-within-a-tcl-thread