queue

Summary

This module of the tcllib data structures collection provides the data structure portion of a queue.

See Also

Stacks and Queues
a description about what a queue is.
pqueue
A Pairing-heap priority queue in Tcl

Documentation

see Tcllib

Description

Examples

The most basic example:

package require struct::queue

set Q [struct::queue]

$Q put T1
$Q put T2
$Q put T3 T4 T5

while {[$Q size]} {
    puts [$Q get]
}

$Q destroy

Misc


SEH 2004-12-10: I have found out to my regret that it is not really possible to use [queue] in loop structures, because the "peek" and "get" commands act differently when the queue size is 1 than when it is any number > 1.

It would be nice to be able to do something like:

foreach item [$queue peek [$queue size]] {<do stuff>}

but if [$queue size] is 1, then the value is returned as a string value, whereas if it's 2, the values are returned as a list. So you can't use the above construction unless you know all queue values will look the same as strings or lists. For example:

%set q [struct::queue]
%$q put "a b"
%foreach item [$q peek [$q size]] {puts $item}
a
b
%$q put "c d"
%foreach item [$q peek [$q size]] {puts $item}
a b
c d

This behavior is documented and hence not actually a bug, but as a practical matter it makes the [queue] structure useless to me.


schlenk: I think the original queue author thought of that as a convenience. Maybe he should just add an lpeek subcommand that does what you want.

This should implement it:

proc ::struct::queue::_lpeek {name {count 1}} {
    variable queues
    if {$count < 1} {
        error "invalid item count $count"
    }

    if {$count > [llength $queues($name)]} {
        error "insufficient items in queue to fill request"
    }

    set index [expr {$count - 1}]
    return [lrange $queues($name) 0 $index]
}

btw, the current queue implementation is smart enough so you just define this after package require ::struct::queue and have lpeek working for your code, but its a hack nonetheless

SEH: I nominate this for inclusion into tcllib.

RHS: I'd say a better solution, overall, would be to make the current peek only look at the single element specified by N, while lpeek would do as above (return a list of the first N elements, even if N is 1).

schlenk: Please file a feature request at the sourceforge tcllib project, so it gets remembered/done. I could do it, but I'm not the maintainer for queue (prioqueue has the same issue btw.). And aku is on vacation at the moment...