等待组实现

huangapple go评论66阅读模式
英文:

Wait Group Implementation

问题

有人可以通过给出一个简单的示例代码来展示Wait Group是如何工作或如何实现的吗(最好像这样给出示例)?谢谢。

英文:

Can anybody show me by giving a simple example code how Wait Group works or can be implemented (better if it is given for example like this)? Thanks.

答案1

得分: 0

我不认为等待组(或同步互斥锁)可以用于你的示例。

英文:

I don't think wait group (or sync-mutex) can be implemented for your example.

答案2

得分: 0

它是这样实现的 like this. 等待组实现

英文:

It is implemented like this. 等待组实现

答案3

得分: 0

我找到了一个关于并发Go协程互斥的答案。代码在http://play.golang.org/p/bdBRtA6vS7。谢谢。

英文:

I found an answer of it i.e. on Mutual Exclusion of Concurrent Go Routine's. And code is on http://play.golang.org/p/bdBRtA6vS7. Thanks.

答案4

得分: 0

一个更简单的等待方式是使用堆栈,你将一个项目放在堆栈上,然后当任务完成时将其弹出。WaitGroup将保持代码,直到堆栈为空。下面的代码示例可以帮助你理解这个概念,它旨在管理一个Go函数的多线程行为...

package main

import "sync"

var wg sync.WaitGroup

func main() {
    wg.Add(1) // 压入1
    go func() {
        // 在这里执行一些代码
        wg.Done() // 弹出1
    }()
    
    wg.Add(1) // 压入1
    go func() {
        // 在这里执行一些代码
        wg.Done() // 弹出1
    }()
    
    wg.Add(1) // 压入1
    go func() {
        // 在这里执行一些代码
        wg.Done() // 弹出1
    }()
    
    wg.Wait() // 直到没有更多的项目需要弹出
    // 在这里执行剩余的代码
}
英文:

A simpler wait to see this is like a stack, you place an item on the stack, and then when a task is finished you pop it off. the WaitGroup will hold the code until the stack is empty. see the code below for an example that in its simplicity, should be able to help. it is designed to manage multi threaded behaviour that is a go function...

package main

import ("sync")

var (wg sync.WaitGroup )
func main() {
	wg.Add(1). //Push 1
	go func() {
        // Do some code here
		wg.Done() //pop 1
	}()
	wg.Add(1) //Push 1
	go func() {
        // Do some code here
		wg.Done() //pop 1
	}()
	wg.Add(1) //Push 1
	go func() {
        // Do some code here
		wg.Done() //Pop 1
	}()
	wg.Wait() // Until no more items to pop.
    //Do the rest of your code here.
}

huangapple
  • 本文由 发表于 2011年11月30日 05:06:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/8317727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定