Black Lives Matter. Support the Equal Justice Initiative.

Source file src/sync/example_test.go

Documentation: sync

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sync_test
     6  
     7  import (
     8  	"fmt"
     9  	"sync"
    10  )
    11  
    12  type httpPkg struct{}
    13  
    14  func (httpPkg) Get(url string) {}
    15  
    16  var http httpPkg
    17  
    18  // This example fetches several URLs concurrently,
    19  // using a WaitGroup to block until all the fetches are complete.
    20  func ExampleWaitGroup() {
    21  	var wg sync.WaitGroup
    22  	var urls = []string{
    23  		"http://www.golang.org/",
    24  		"http://www.google.com/",
    25  		"http://www.somestupidname.com/",
    26  	}
    27  	for _, url := range urls {
    28  		// Increment the WaitGroup counter.
    29  		wg.Add(1)
    30  		// Launch a goroutine to fetch the URL.
    31  		go func(url string) {
    32  			// Decrement the counter when the goroutine completes.
    33  			defer wg.Done()
    34  			// Fetch the URL.
    35  			http.Get(url)
    36  		}(url)
    37  	}
    38  	// Wait for all HTTP fetches to complete.
    39  	wg.Wait()
    40  }
    41  
    42  func ExampleOnce() {
    43  	var once sync.Once
    44  	onceBody := func() {
    45  		fmt.Println("Only once")
    46  	}
    47  	done := make(chan bool)
    48  	for i := 0; i < 10; i++ {
    49  		go func() {
    50  			once.Do(onceBody)
    51  			done <- true
    52  		}()
    53  	}
    54  	for i := 0; i < 10; i++ {
    55  		<-done
    56  	}
    57  	// Output:
    58  	// Only once
    59  }
    60  

View as plain text