Version 1 of Sharing a common logger thread example

Updated 2003-06-13 10:01:43

From a post of Zoran Vasiljevic to comp.lang.tcl on 13. June 2003:

... In order to achieve what you'd like to get, I'd create a logger thread and add a thin layer above your Log and Trace procdures which would route commands to exectution on the logger thread. This is easibly achievable but requires little more work on your side.

 package require Thread

 # Create the logger thread
 set logtid [thread::create {
    source Log.tcl
    thread::wait
 }]

The "Log" command is located in "Log.tcl" and may look like:

 proc Log {msg} {
    if {[info exists ::logtid] && $::logtid != [thread::id]} {
        thread::send $::logtid "Log $msg"
    } else {
        puts stderr $msg
    }
 }

So, throughout the code you can now use use "Log" procedure and it will re-route the command for the execution to the logtid thread. This will simply puts the log message to stderr. In each thread which needs to use the logger thread you'd simply load the Log.tcl and set the logtid global variable:

 set workertid [thread::create [subst {
    set logtid $logtid
    source Log.tcl
    thread::wait
 }]

Category Threads | Category Example