This is a creation in Article, where the information may have evolved or changed.
This blog and Rayxxzhang blog to keep in sync with the update, reprint please indicate from Rayxxzhang Blog-golang implement with priority channel
The general Go language uses multiple channel
methods simultaneously using the select
/ case
statement mate <-
operators, such as
select {case <- chan1: // do somethingcase <- chan2: // do something}
But this implementation is the chan1
same as the chan2
priority level. If you want to implement a priority, you channel
need to use the defalut
statement.
In the Go language, if select
case
there is no clause in/, the default
program blocks in select
until one of the case
statements receives the data.
If there is a default
statement, it will not block, if the case
data received, the execution case
of the statement, if the case
signal is not received, will execute defalut
the statement in, and then jump out of the select
block.
Use this feature to implement a queue with priority channel
. A 2-priority channel
example is achieved by using multiple layers select
, placing high priority channel
behind the outermost select
statement case
, and following a default
statement to avoid blocking when high-priority channel
data is not available.
defalut
is still a statement in which the select
select
high-priority and low-priority case
are placed and no default
statements are in the statement. This will block the inner layer select
until one of the data is case
received.
This implementation is equivalent to the high priority of the channel
lower priority than the opportunity to be processed once, that is, the outer select
layer, only the high priority without data, will only execute the inner layers select
, when the first generation of data channel
is executed.
That is, when high-priority and low-priority have data, high-priority is processed first, that is, the priority is achieved. Examples are as follows:
for {select {case data: = <-highchan:handlehigh (data) default : select {case data: = <-highchan:handlehigh (data) case data: = <-lowchan:handlelow (data)}}}