user1497818
user1497818

Reputation: 375

How to create a thread in tcl 8.4

I am new to tcl. I want to create a thread in tcl which should keep calling itself in background.

#!/usr/bin/env tclsh

set serPort [open "/dev/ttyS0" RDWR]

fconfigure $serPort  -mode 115200,n,8,1 -blocking 0 

while { 1 } {
set data [gets  $chan]
puts $data

}

I want to avoid using the above while loop and create a repeatable thread for the functionality inside the while loop. Basically i am connecting the COM1 of my PC to a device and getting the serial data from the device. But if there is no data on the port it still doesn't come out of loop even if i use "eof" command. That is the reason i want to create the thread.

I am planning to use Tcl_CreateThread for that but I don't understood how to use it

Upvotes: 2

Views: 644

Answers (1)

kostix
kostix

Reputation: 55443

Don't do that. Instead, use the usual Tcl's idiom for working with non-blocking channels: set up a handler for the "channel readable" event, and enter the event loop; when the device sends data to the port you opened, the OS passes the data to your application and the callback gets called.

A minimal program to demonstrate the concept looks like this:

proc my_read_handler ch {
    set data [read $ch]
    if {[eof $ch]} {
        close $ch
        set ::forever done ;# this makes the call to `vwait` below to quit
        return
    }
    # Otherwise process the data here ...
}

set serPort [open "/dev/ttyS0" RDWR]

fconfigure $serPort -mode 115200,n,8,1 -blocking no
fileevent $serPort readable [list my_read_handler $serPort]

vwait ::forever ;# the program enters the event loop here

Read more on this in the examples.

Several observations:

  • The EOF only happens when the remote side closes. If you call close on your channel, the "readable" even won't be called in this case.
  • If you're writing a Tk application, it will already have an event loop, so no calls to vwait are necessary (moreover, they're highly advised against, as this will re-enter the event loop): you just open your device, say, in a code which executes when the users clicks a button, set up the readable callback on the acquired channel and then just do the rest of the processing in that callback (as shown above).

Read this (and the links there) for more info on the event-oriented programming. Also search the wiki — it contains lots of examples and background knowledge.

Upvotes: 5

Related Questions