本文整理匯總了Golang中sync.WaitGroup.Add方法的典型用法代碼示例。如果您正苦於以下問題:Golang WaitGroup.Add方法的具體用法?Golang WaitGroup.Add怎麽用?Golang WaitGroup.Add使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sync.WaitGroup
的用法示例。
在下文中一共展示了WaitGroup.Add方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
introText := "SIMPLE TWITTER REFORMATTER \n (╯°□°)╯︵ ┻━┻) \n"
fmt.Printf(introText)
key := flag.String("key", "nokey", "Twitter consumer key")
secret := flag.String("sec", "nosecret", "Twitter consumer secret")
debug := flag.Bool("debug", false, "Debug logging level")
numTweets := flag.Int("num", 3, "Number of tweets to retrieve")
flag.Parse()
access_token, err := getBearerToken(*key, *secret, *debug)
if err != nil || access_token == "" {
log.Fatal("Could not retrieve token to make twitter API request")
os.Exit(1)
}
// Create a very basic channel with tweets getting passed into the expander
// Wait for it to finish executing before quiting.
var tweetChannel chan string = make(chan string)
var wg sync.WaitGroup
wg.Add(1)
go tweetRetriever(access_token, *numTweets, tweetChannel, &wg, *debug)
go textExpander(tweetChannel)
wg.Wait()
}
示例2: Run
// Run runs the query concurrently, and returns the results.
func (q *Query) Run() []interface{} {
rand.Seed(time.Now().UnixNano())
var w sync.WaitGroup
var l sync.Mutex
places := make([]interface{}, len(q.Journey))
for i, r := range q.Journey {
w.Add(1)
go func(types string, i int) {
defer w.Done()
response, err := q.find(types)
if err != nil {
log.Println("Failed to find places:", err)
return
}
if len(response.Results) == 0 {
log.Println("No places found for", types)
return
}
for _, result := range response.Results {
for _, photo := range result.Photos {
photo.URL = "https://maps.googleapis.com/maps/api/place/photo?" +
"maxwidth=1000&photoreference=" + photo.PhotoRef + "&key=" + APIKey
}
}
randI := rand.Intn(len(response.Results))
l.Lock()
places[i] = response.Results[randI]
l.Unlock()
}(r, i)
}
w.Wait() // wait for everything to finish
return places
}
示例3: runPipeline
func (a *apiServer) runPipeline(pipelineInfo *pps.PipelineInfo) error {
ctx, cancel := context.WithCancel(context.Background())
a.lock.Lock()
a.cancelFuncs[*pipelineInfo.Pipeline] = cancel
a.lock.Unlock()
var loopErr error
//TODO this gets really weird with branching... we need to figure out what that looks like.
mostRecentCommit := make(map[pfs.Repo]*pfs.Commit)
var lock sync.Mutex
var wg sync.WaitGroup
for _, inputRepo := range pipelineInfo.InputRepo {
inputRepo := inputRepo
wg.Add(1)
go func() {
defer wg.Done()
var lastCommit *pfs.Commit
listCommitRequest := &pfs.ListCommitRequest{
Repo: inputRepo,
CommitType: pfs.CommitType_COMMIT_TYPE_READ,
From: lastCommit,
Block: true,
}
commitInfos, err := a.pfsAPIClient.ListCommit(ctx, listCommitRequest)
if err != nil && loopErr == nil {
loopErr = err
return
}
for _, commitInfo := range commitInfos.CommitInfo {
lock.Lock()
mostRecentCommit[*inputRepo] = commitInfo.Commit
var commits []*pfs.Commit
for _, commit := range mostRecentCommit {
commits = append(commits, commit)
}
lock.Unlock()
if len(commits) < len(pipelineInfo.InputRepo) {
// we don't yet have a commit for every input repo so there's no way to run the job
continue
}
outParentCommit, err := a.bestParent(pipelineInfo, commitInfo)
if err != nil && loopErr == nil {
loopErr = err
return
}
_, err = a.jobAPIClient.CreateJob(
ctx,
&pps.CreateJobRequest{
Spec: &pps.CreateJobRequest_Pipeline{
Pipeline: pipelineInfo.Pipeline,
},
InputCommit: []*pfs.Commit{commitInfo.Commit},
OutputParent: outParentCommit,
},
)
}
}()
}
wg.Wait()
return loopErr
}
示例4: main
func main() {
var wg sync.WaitGroup
sc := make(chan os.Signal, 1)
signal.Notify(sc,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
go func() {
sig := <-sc
running = false
fmt.Printf("main:Got signal:%v", sig)
}()
fmt.Printf("main:Mock get id process start!\n")
db, err := GetDatabase()
if err != nil {
fmt.Printf("main:GetDatabase error:%s\n", err.Error())
return
}
idGenerator, err := GetIdGenerator(db, idKey)
if err != nil {
fmt.Printf("main:GetIdGenerator error:%s\n", err.Error())
return
}
wg.Add(1)
go MockGetId(idGenerator, db, &wg)
wg.Wait()
}
示例5: connectSwarms
func connectSwarms(t *testing.T, ctx context.Context, swarms []*Swarm) {
var wg sync.WaitGroup
connect := func(s *Swarm, dst peer.ID, addr ma.Multiaddr) {
// TODO: make a DialAddr func.
s.peers.AddAddr(dst, addr, peer.PermanentAddrTTL)
if _, err := s.Dial(ctx, dst); err != nil {
t.Fatal("error swarm dialing to peer", err)
}
wg.Done()
}
log.Info("Connecting swarms simultaneously.")
for _, s1 := range swarms {
for _, s2 := range swarms {
if s2.local != s1.local { // don't connect to self.
wg.Add(1)
connect(s1, s2.LocalPeer(), s2.ListenAddresses()[0]) // try the first.
}
}
}
wg.Wait()
for _, s := range swarms {
log.Infof("%s swarm routing table: %s", s.local, s.Peers())
}
}
示例6: cliCloseListener
func cliCloseListener(c *cli.Context) {
args := c.Args()
if len(args) == 0 {
Exit("Must specify listenAddr to stop")
}
listenAddr := args[0]
command := btypes.CommandCloseListener{
Addr: listenAddr,
}
wg := sync.WaitGroup{}
failed := 0
for _, remote := range Config.Remotes {
wg.Add(1)
go func(remote string) {
defer wg.Done()
response, err := CloseListener(Config.PrivKey, remote, command)
if err != nil {
failed++
fmt.Printf("%v failure. %v\n", remote, err)
} else {
fmt.Printf("%v success. %v\n", remote, response)
}
}(remote)
}
wg.Wait()
if 0 < failed {
os.Exit(1)
}
}
示例7: DeprecateImages
// Modify renames the given images
func (g *GceImages) DeprecateImages(opts *DeprecateOptions) error {
var (
wg sync.WaitGroup
mu sync.Mutex // protects multiErrors
multiErrors error
)
for _, n := range opts.Names {
wg.Add(1)
go func(name string) {
st := &compute.DeprecationStatus{
State: opts.State,
}
_, err := g.svc.Deprecate(g.config.ProjectID, name, st).Do()
if err != nil {
mu.Lock()
multiErrors = multierror.Append(multiErrors, err)
mu.Unlock()
}
wg.Done()
}(n)
}
wg.Wait()
return multiErrors
}
示例8: Gather
// Gathers data for all servers.
func (h *HttpJson) Gather(acc telegraf.Accumulator) error {
var wg sync.WaitGroup
errorChannel := make(chan error, len(h.Servers))
for _, server := range h.Servers {
wg.Add(1)
go func(server string) {
defer wg.Done()
if err := h.gatherServer(acc, server); err != nil {
errorChannel <- err
}
}(server)
}
wg.Wait()
close(errorChannel)
// Get all errors and return them as one giant error
errorStrings := []string{}
for err := range errorChannel {
errorStrings = append(errorStrings, err.Error())
}
if len(errorStrings) == 0 {
return nil
}
return errors.New(strings.Join(errorStrings, "\n"))
}
示例9: ReadWrite
// ReadWrite does read and write in parallel.
// qRead is num goroutines for reading.
// qWrite is num goroutines for writing.
// Assume n divisible by (qRead + qWrite).
func ReadWrite(n, qRead, qWrite int, newFunc func() HashMap, b *testing.B) {
q := qRead + qWrite
check(n, q)
work := intPairArray(n)
b.StartTimer()
for i := 0; i < b.N; i++ { // N reps.
h := newFunc()
var wg sync.WaitGroup
for j := 0; j < qRead; j++ { // Read goroutines.
wg.Add(1)
go func(j int) {
defer wg.Done()
start, end := workRange(n, q, j)
for k := start; k < end; k++ {
h.Get(work[k].Key)
}
}(j)
}
for j := qRead; j < q; j++ { // Write goroutines.
wg.Add(1)
go func(j int) {
defer wg.Done()
start, end := workRange(n, q, j)
for k := start; k < end; k++ {
h.Put(work[k].Key, work[k].Val)
}
}(j)
}
wg.Wait()
}
}
示例10: TestOutputHTTPSSL
func TestOutputHTTPSSL(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
// Origing and Replay server initialization
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wg.Done()
}))
input := NewTestInput()
output := NewHTTPOutput(server.URL, &HTTPOutputConfig{})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
wg.Add(2)
input.EmitPOST()
input.EmitGET()
wg.Wait()
close(quit)
}
示例11: TestHTTPOutputKeepOriginalHost
func TestHTTPOutputKeepOriginalHost(t *testing.T) {
wg := new(sync.WaitGroup)
quit := make(chan int)
input := NewTestInput()
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Host != "custom-host.com" {
t.Error("Wrong header", req.Host)
}
wg.Done()
}))
defer server.Close()
headers := HTTPHeaders{HTTPHeader{"Host", "custom-host.com"}}
Settings.modifierConfig = HTTPModifierConfig{headers: headers}
output := NewHTTPOutput(server.URL, &HTTPOutputConfig{Debug: false, OriginalHost: true})
Plugins.Inputs = []io.Reader{input}
Plugins.Outputs = []io.Writer{output}
go Start(quit)
wg.Add(1)
input.EmitGET()
wg.Wait()
close(quit)
Settings.modifierConfig = HTTPModifierConfig{}
}
示例12: TestMultipleGetEmpty
func TestMultipleGetEmpty(t *testing.T) {
q := New(10)
var wg sync.WaitGroup
wg.Add(2)
results := make([][]interface{}, 2)
go func() {
wg.Done()
local, err := q.Get(1)
assert.Nil(t, err)
results[0] = local
wg.Done()
}()
go func() {
wg.Done()
local, err := q.Get(1)
assert.Nil(t, err)
results[1] = local
wg.Done()
}()
wg.Wait()
wg.Add(2)
q.Put(`a`, `b`, `c`)
wg.Wait()
if assert.Len(t, results[0], 1) && assert.Len(t, results[1], 1) {
assert.True(t, (results[0][0] == `a` && results[1][0] == `b`) ||
(results[0][0] == `b` && results[1][0] == `a`),
`The array should be a, b or b, a`)
}
}
示例13: TestStoreRangeUpReplicate
// TestStoreRangeUpReplicate verifies that the replication queue will notice
// under-replicated ranges and replicate them.
func TestStoreRangeUpReplicate(t *testing.T) {
defer leaktest.AfterTest(t)
mtc := startMultiTestContext(t, 3)
defer mtc.Stop()
// Initialize the gossip network.
var wg sync.WaitGroup
wg.Add(len(mtc.stores))
key := gossip.MakePrefixPattern(gossip.KeyStorePrefix)
mtc.stores[0].Gossip().RegisterCallback(key, func(_ string, _ roachpb.Value) { wg.Done() })
for _, s := range mtc.stores {
s.GossipStore()
}
wg.Wait()
// Once we know our peers, trigger a scan.
mtc.stores[0].ForceReplicationScanAndProcess()
// The range should become available on every node.
if err := util.IsTrueWithin(func() bool {
for _, s := range mtc.stores {
r := s.LookupReplica(roachpb.RKey("a"), roachpb.RKey("b"))
if r == nil {
return false
}
}
return true
}, replicationTimeout); err != nil {
t.Fatal(err)
}
}
示例14: Run
func (t *testRunner) Run() bool {
reschan := make(chan *testResult)
wg := sync.WaitGroup{}
for _, route := range t.api.Routes {
wg.Add(1)
go func(route Route) {
reschan <- t.invokeTest(route.Path, route.Test)
wg.Done()
}(route)
}
go func() {
wg.Wait()
close(reschan)
}()
success := true
for res := range reschan {
if res == nil {
continue
}
if res.isFailure() {
success = false
}
}
return success
}
示例15: Run
func (n *network) Run(ctx context.Context) {
wg := sync.WaitGroup{}
log.Info("Watching for new subnet leases")
evts := make(chan []subnet.Event)
wg.Add(1)
go func() {
subnet.WatchLeases(ctx, n.sm, n.name, n.lease, evts)
wg.Done()
}()
n.rl = make([]netlink.Route, 0, 10)
wg.Add(1)
go func() {
n.routeCheck(ctx)
wg.Done()
}()
defer wg.Wait()
for {
select {
case evtBatch := <-evts:
n.handleSubnetEvents(evtBatch)
case <-ctx.Done():
return
}
}
}