小编Kom*_*omu的帖子

Golang程序挂起而没有完成执行

我有以下golang程序;

package main

import (
    "fmt"
    "net/http"
    "time"
)

var urls = []string{
    "http://www.google.com/",
    "http://golang.org/",
    "http://yahoo.com/",
}

type HttpResponse struct {
    url      string
    response *http.Response
    err      error
    status   string
}

func asyncHttpGets(url string, ch chan *HttpResponse) {
    client := http.Client{}
    if url == "http://www.google.com/" {
        time.Sleep(500 * time.Millisecond) //google is down
    }

    fmt.Printf("Fetching %s \n", url)
    resp, err := client.Get(url)
    u := &HttpResponse{url, resp, err, "fetched"}
    ch <- u
    fmt.Println("sent to chan")
}

func main() {
    fmt.Println("start")
    ch := make(chan …
Run Code Online (Sandbox Code Playgroud)

channel go goroutine

2
推荐指数
1
解决办法
2335
查看次数

为什么我认为并行的程序不平行

package main

import (
    "fmt"
    "runtime"
    "sync"
)

var wg sync.WaitGroup

func alphabets() {
    for char := 'a'; char < 'a'+26; char++ {
        fmt.Printf("%c ", char)
    }
    wg.Done() //decrement number of goroutines to wait for
}

func numbers() {
    for number := 1; number < 27; number++ {
        fmt.Printf("%d ", number)
    }
    wg.Done()
}

func main() {
    runtime.GOMAXPROCS(2)
    wg.Add(2) //wait for two goroutines

    fmt.Println("Starting Go Routines")
    go alphabets()
    go numbers()

    fmt.Println("\nWaiting To Finish")

    wg.Wait() //wait for the two goroutines to …
Run Code Online (Sandbox Code Playgroud)

parallel-processing concurrency go

0
推荐指数
1
解决办法
158
查看次数