简单的队列模型示例 [英] Simple queue model example

查看:31
本文介绍了简单的队列模型示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个简单的程序来演示 Go 中的队列是如何工作的.我只需要在队列中添加数字 1 到 10 并使用另一个线程并行地从队列中拉出它们.

Is there a simple program which demonstrates how queues work in Go. I just need something like add number 1 to 10 in queue and pull those from the queue in parallel using another thread.

推荐答案

你可以使用channel(并发使用安全)和wait group同时从队列中读取

You could use channel(safe for concurrent use) and wait group to read from queue concurrently

package main

import (
    "fmt"
    "sync"
)

func main() {
    queue := make(chan int)

    wg := new(sync.WaitGroup)
    wg.Add(1)
    defer wg.Wait()

    go func(wg *sync.WaitGroup) {
        for {

            r, ok := <-queue
            if !ok {
                wg.Done()
                return
            }

            fmt.Println(r)
        }
    }(wg)

    for i := 1; i <= 10; i++ {
        queue <- i
    }

    close(queue)
}

游乐场链接:https://play.golang.org/p/A_Amqcf2gwU

这篇关于简单的队列模型示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆