2014-04-11 Marc Glisse <marc.glisse@inria.fr>
[official-gcc.git] / libgo / go / sync / example_test.go
blobbdd3af6fedaa4bb25b7cb6b2990a5aa171209612
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.
5 package sync_test
7 import (
8 "fmt"
9 "sync"
12 type httpPkg struct{}
14 func (httpPkg) Get(url string) {}
16 var http httpPkg
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/",
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)
38 // Wait for all HTTP fetches to complete.
39 wg.Wait()
42 func ExampleOnce() {
43 var once sync.Once
44 onceBody := func() {
45 fmt.Println("Only once")
47 done := make(chan bool)
48 for i := 0; i < 10; i++ {
49 go func() {
50 once.Do(onceBody)
51 done <- true
52 }()
54 for i := 0; i < 10; i++ {
55 <-done
57 // Output:
58 // Only once