- Learn Data Structures and Algorithms with Golang
- Bhagvan Kommadi
- 120字
- 2021-06-24 15:37:50
The New method
The New method on Queue initializes message, queuePass, and queueTicket with nil values. The make method creates a Queue with a chan integer parameter, as follows:
// New method initializes queue
func (queue *Queue) New() {
queue.message = make(chan int)
queue.queuePass= make(chan int)
queue.queueTicket= make(chan int)
}
In the following code example, the Go routine handles selecting the message based on the type of message and the respective queue to process it:
go func() {
var message int
for {
select {
case message = <-queue.message:
switch message {
case messagePassStart:
queue.waitPass++
case messagePassEnd:
queue.playPass = false
case messageTicketStart:
queue.waitTicket++
case messageTicketEnd:
queue.playTicket = false
}
if queue.waitPass > 0 && queue.waitTicket > 0 && !queue.playPass && !queue.playTicket {
queue.playPass = true
queue.playTicket = true
queue.waitTicket--
queue.waitPass--
queue.queuePass <- 1
queue.queueTicket <- 1
}
}
}
}()
}