I'm pretty much done, just tidying up, that vwait was the last hurdle.
I had looked at tpool. I found it a bit daunting since I then had no
experience with threads. And no examples in the man page.
So as a learning exercise, I decided to build my own. However, my task
model is not tcl-threads rpc-like, but rather the more familiar
procedure call/return.
Here's a small example which lets one do heavy compute in a separate
thread to keep the main thread's gui responsive:
#--------------------------------------------------
proc sumtwo {a1 a2} { ;# add 2 args plus simulate computing
for {set n 0} {$n < 10000000 } {incr n} {incr m}
return [expr {$a1+$a2}]
}
Task summer {sumtwo} { ;# import sumtwo proc into new thread
twait -> a1 a2 ;# get work & "lassign" to a1 and a2
treturn [sumtwo $a1 $a2] ;# call sumtoo, return result, then repeat
}
tcall $summer answer 5 10 ;# call sync and wait for answer
puts "answer = $answer"
#--------------------------------------------------
I think this shows the simplicity I was aiming for. Well, it seems
simple to me, but that's always the advantage of "building your own". I
do think any beginner tcl programmer could learn to use this quite easily.
This can then easily extend to the multiple server model by just
encoding the task name as,
Task helper1/summer .... ;# any number, all use same "summer" queue
And we can also make async calls, using separate result array elements:
tcall $summer -async answer(0) 5 10
tcall $summer -async answer(1) 6 10
...
foreach t {0 1 ...} { ;# and wait for all to complete
tvwait answer($t)
}
So, a Task is sort of a wrapper-class to threads, and one thread or
multiple threads look almost identical.
The goal was to make it look and work as much like a normal procedure
call as possible. I think it's all working, and only about 400 lines of
actual code. Lots more too, like a debugging "puts", error catching, and
some info like tools.
I've always preferred building tools to normal coding. My favorite quote
of all times was by Brian Kernighan:
"I'd rather write programs that write programs, than write programs".