TCL在多线程方面表现也非常出色.而且你会发现他的多线程编程非常简单,下面是从<<
Practical Programming in Tcl and Tk, Fourth Edition>>上面摘抄的几个有关多线程的例子,做为备忘,明天有空的话,我会加入一些更高级的多线程编程概念.
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...
|
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!"
|
Using joinable threads to detect thread termination
package require Thread
puts "*** I'm thread [thread::id]"
# Create 3 threads
for {set thread 1} {$thread <= 3} {incr thread} {
set id [thread::create -joinable {
# 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"
lappend threadIds $id
} ;# for
puts "*** Existing threads: [thread::names]"
# Wait until all other threads are finished
foreach id $threadIds {
thread::join $id
}
puts "*** That's all, folks!"
|
阅读(6722) | 评论(0) | 转发(0) |