TABLE OF CONTENTS


::pwtk::thread

SYNOPSIS

proc ::pwtk::thread {args} {

USAGE

   thread ?-r? script ?script? ?script ...?

OPTIONS

PURPOSE

Arranges for a script, which is formed by concatenating all the script arguments, to run in a new thread in the background. Hence, the command returns immediately. To wait for threads to finish, use the ::pwtk::thread_wait command.

WARNING

Note that bgs (aka backgrounds, see ::pwtk::bg) are safer to use than threads because bgs are completely independent from one another, whereas threads share some resources such as current-working directory and enviromental variables. If one thread changes the current working directory, then that change affects all threads.

ARGUMENTS

The script to be executed in a new thread is formed by concatenating all the script arguments. For example, the following two examples are equivalent:

      ::pwtk::thread print "I am a new thread"

      ::pwtk::thread {
          print "I am a new thread"
      }

RETURN VALUE

SOURCE

    variable thread

    thread_init    

    set redirect 0
    if { [lindex $args 0] eq "-r" } {
        set redirect 1
        set args [lrange $args 1 end]
    }
    if { [llength $args] == 1 } {
        set args [concat {*}$args]
    }

    incr thread(count)
        
    # create a new thread 

    #set id [::thread::create $thread(initcmd)]
    set id [::thread::create [::pwtk::thread_initscript_]]
    lappend thread(ids) $id

    set head [file tail [file rootname [info script]]]
    set log thread.$head.$thread(count).log

    print THREAD "Running a script in a new thread"
    print "
Thread No.$thread(count): ID = $id"    
    if { $redirect } {
        print "Output of thread-$id is redirected to a log file:  $log"
    }
    print "Script to run in this thread:\n\n[string trim $args]\n"

    # save the current input data state
    #set peekData [::pwtk::input::peek]
    #::thread::send -async $id [list ::pwtk::input::load_state $peekData]

    #set script [::pwtk::propagate_dump]\n$args; # N.B. ::pwtk::thread_initscript_ takes care of "propagate" now
    set script $args
    
    if { $redirect } {
        ::thread::send -async $id [list ::pwtk::redirect_stdout_to $log $script]
    } else {
        ::thread::send -async $id $script
    }

    return $id
}