Skip to main content
Version: 2.8.x(Latest)

Basic Usage

Using Queue.Pop

package main

import (
"fmt"
"time"
"github.com/gogf/gf/v2/os/gtimer"
"github.com/gogf/gf/v2/container/gqueue"
)

func main() {
q := gqueue.New()

// Data producer, writes data to the queue every second
gtimer.SetInterval(time.Second, func() {
v := gtime.Now().String()
q.Push(v)
fmt.Println("Push:", v)
})

// Close the queue after 3 seconds
gtimer.SetTimeout(3*time.Second, func() {
q.Close()
})

// Consumer, continuously reads queue data and outputs to the terminal
for {
if v := q.Pop(); v != nil {
fmt.Println(" Pop:", v)
} else {
break
}
}

// The program exits immediately when the queue is closed at the third second, so only 2 seconds of data will be printed in the result. After execution, the output will be:
// Output:
// Push: 2021-09-07 14:03:00
// Pop: 2021-09-07 14:03:00
// Push: 2021-09-07 14:03:01
// Pop: 2021-09-07 14:03:01
}

Using Queue.C

package main

import (
"context"
"fmt"
"time"

_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
"github.com/gogf/gf/v2/container/gqueue"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/os/gtimer"
)

func main() {
queue := gqueue.New()
gtimer.AddTimes(gctx.GetInitCtx(), time.Second, 3, func(ctx context.Context) {
queue.Push(gtime.Now().String())
})
for {
select {
case queueItem := <-queue.C:
fmt.Println(queueItem)

case <-time.After(3 * time.Second):
fmt.Println("timeout, exit loop")
return
}
}
}

Enqueue/Dequeue Elements

package main

import (
"fmt"
"time"
"github.com/gogf/gf/v2/os/gtimer"
"github.com/gogf/gf/v2/container/gqueue"
)

func main() {
q := gqueue.New()

for i := 0; i < 10; i++ {
q.Push(i)
}

fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.Pop())

// Output:
// 0
// 1
// 2
}

Queue Length

package main

import (
"fmt"
"time"
"github.com/gogf/gf/v2/os/gtimer"
"github.com/gogf/gf/v2/container/gqueue"
)

func main() {
q := gqueue.New()

q.Push(1)
q.Push(2)

fmt.Println(q.Len())
// size is an alias for the len method
fmt.Println(q.Size())

// May Output:
// 2
// 2
}

Queue Close

package main

import (
"fmt"
"time"
"github.com/gogf/gf/v2/os/gtimer"
"github.com/gogf/gf/v2/container/gqueue"
)

func main() {
q := gqueue.New()

for i := 0; i < 10; i++ {
q.Push(i)
}

fmt.Println(q.Pop())
q.Close()
fmt.Println(q.Pop())
fmt.Println(q.Len())

// Output:
// 0
// <nil>
// 0
}

gqueue and glist

The underlying implementation of gqueue is based on the glist linked list, which provides dynamic size characteristics. Writing data when the queue is full or reading data when the queue is empty will result in blocking.

glist is a concurrent-safe linked list and can behave like a normal list when the concurrent-safe feature is turned off, without encountering blocking during data storage and retrieval.