Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8336482
  • 博文数量: 1413
  • 博客积分: 11128
  • 博客等级: 上将
  • 技术积分: 14685
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-13 10:03
个人简介

follow my heart...

文章分类

全部博文(1413)

文章存档

2013年(1)

2012年(5)

2011年(45)

2010年(176)

2009年(148)

2008年(190)

2007年(293)

2006年(555)

分类:

2009-03-19 23:54:15

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!"

阅读(6515) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~