我是tcl的新手.我想在tcl中创建一个线程,它应该继续在后台调用自己.
#!/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
}
Run Code Online (Sandbox Code Playgroud)
我想避免使用上面的while循环,并为while循环内的功能创建一个可重复的线程.基本上我将PC的COM1连接到设备并从设备获取串行数据.但是如果端口上没有数据,即使我使用"eof"命令,它仍然不会出现循环.这就是我想创建线程的原因.
我打算使用Tcl_CreateThread,但我不明白如何使用它
不要那样做.相反,使用通常的Tcl惯用法来处理非阻塞通道:为"通道可读"事件设置处理程序,并进入事件循环; 当设备将数据发送到您打开的端口时,操作系统会将数据传递给您的应用程序,并调用回调.
演示概念的最小程序如下所示:
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
Run Code Online (Sandbox Code Playgroud)
在示例中阅读更多相关内容.
几点意见:
close给你的频道,在这种情况下甚至不会调用"可读".vwait(此外,他们强烈反对,因为这将重新进入事件循环):您只需打开您的设备,说,在其执行时的用户点击一个按钮一个代码,设置了可读回调所获取的信道,然后只是做的处理的其余部分在该回调(如上所示).阅读本文(及其中的链接),了解有关面向事件编程的更多信息.还搜索维基 - 它包含大量示例和背景知识.