tk借助Thread包实现多线程实例

对于有需求进行多线程操作,或者有界面相关操作的运算以及后台处理情况,可以通过多现场操作。

一下例子:Creating a separate thread to perform a lengthy operation

package require Thread

# Create a separate thread to search the current directory
# and all its subdirectories, recursively, for all files
# ending in the extension ".tcl". Store the results in the
# file "files.txt".

thread::create {
   # Load the Tcllib fileutil package to use its
   # findByPattern procedure.

   package require fileutil

   set files [fileutil::findByPattern [pwd] *.tcl]

   set fid [open files.txt w]
   puts $fid [join $files \n]
   close $fid
}

# The main thread can perform other tasks in parallel...

对于需要在{}中体现变量数据的情况,可以通过如下结构实现:

thread::create [list exec app.exe]

以下实例:在应用中创建多线程Creating several threads in an application

package require Thread

puts "*** I'm thread [thread::id]"

# Create 3 threads

for {set thread 1} {$thread <= 3} {incr thread} {
   set id [thread::create {

      # Print a hello message 3 times, waiting
      # a random amount of time between messages

      for {set i 1} {$i <= 3} {incr i} {
         after [expr { int(500*rand()) }]
         puts "Thread [thread::id] says hello"
      }

   }] ;# thread::create

   puts "*** Started thread $id"
} ;# for

puts "*** Existing threads: [thread::names]"

# Wait until all other threads are finished

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

puts "*** That's all, folks!"








你可能感兴趣的:(CAE,二次开发,tcl,tcltk)