Go 使用锁和切片实现一个简单的队列

代码示例

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"sync"
)

//使用锁实现一个队列
type SliceQueue struct {
	data []interface{}
	mu sync.Mutex
}

func NewSliceQueue(n int) *SliceQueue {
	return &SliceQueue{data: make([]interface{},0,n)}
}

func (sq *SliceQueue) Enqueue(v interface{})  {
	sq.mu.Lock()
	sq.data = append(sq.data,v)
	sq.mu.Unlock()
}

//出队
func (sq *SliceQueue) Dequeue() interface{} {
	sq.mu.Lock()
	defer sq.mu.Unlock()
	v := sq.data[0]
	sq.data = sq.data[1:]
	return v
}

func main() {
	sq := NewSliceQueue(2)

	consol := bufio.NewScanner(os.Stdin)
	for consol.Scan(){
		action := consol.Text()
		item := strings.Split(action," ")
		switch item[0] {
		case "push":
			if len(item) !=2 {
				fmt.Println("must be set value")
				continue
			}
			sq.Enqueue(item[1])
		case "pop":
			val := sq.Dequeue()
			fmt.Println(val)
		case "quit","exit":
			return
		default:

		}
	}
}

  

posted @ 2021-01-22 12:57  pebblecome  阅读(232)  评论(0)    收藏  举报