标签: goroutine

第一个goroutine例子,奇怪的结果

此示例取自tour.golang.org/#63

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}
Run Code Online (Sandbox Code Playgroud)

输出

hello
world
hello
world
hello
world
hello
world
hello
Run Code Online (Sandbox Code Playgroud)

为什么world只打印4时代而不是5?


编辑:答案可以引用golang规范:

程序执行从初始化主包然后调用main函数开始.当函数main返回时,程序退出.它不等待其他(非主要)goroutines完成.

go goroutine

3
推荐指数
1
解决办法
281
查看次数

等待一个例程完成的正确方法

我想知道在退出程序之前等待程序完成的正确方法是什么.阅读其他一些答案似乎bool chan会做到这一点,就像Playground链接一样

func do_stuff(done chan bool) {
    fmt.Println("Doing stuff")
    done <- true
}

func main() {
    fmt.Println("Main")
    done := make(chan bool)
    go do_stuff(done)
    <-done
    //<-done
}
Run Code Online (Sandbox Code Playgroud)

我这里有两个问题:

  • 为什么< - 完成工作?

  • 如果我取消注释最后一行会发生什么?我有一个死锁错误.这是因为频道是空的,没有其他功能向它发送值?

channel go goroutine

3
推荐指数
2
解决办法
5507
查看次数

golang函数:带返回的并行执行

如何使两个函数的调用f1(2)和f1(1)并行执行,使所有的计划将持续3执行2秒钟没有.

package main

import (
    "fmt"
    "time"
)

// sleeps for `secs` seconds
func f1(secs time.Duration) (result string) {
    fmt.Printf("waiting %V\n", secs)
    time.Sleep(secs * time.Second)
    result = fmt.Sprintf("waited for %d seconds", secs)
    return
}

// prints arg1, arg2
func f2(arg1, arg2 string) {
    fmt.Println(arg1)
    fmt.Println(arg2)
}

// this function executes for 3 seconds, because waits a lot
func runNotParallel() {

    out1 := f1(2)
    out2 := f1(1)
    f2(out1, out2)

}

// golang parallel return functions
// todo: …
Run Code Online (Sandbox Code Playgroud)

go goroutine

3
推荐指数
2
解决办法
6982
查看次数

使用两个返回参数为func创建chan

在boolInt不重新定义功能的情况下创建功能通道是否可行?

package main

func boolInt() (bool, int) {
    return false, 1
}

func main() {
    chanBool := make(chan bool)
    chanInt := make(chan int)
    go func() {
        // chanBool <- boolInt() // error: multiple-value boolInt() in single-value context
        chanBool, chanInt <- boolInt() //  syntax error: unexpected semicolon or newline, expecting := or = or comma
    }()

}
Run Code Online (Sandbox Code Playgroud)

当我尝试在单值上下文中使用它时, chanBool <- boolInt()我得到一个错误: multiple-value boolInt() in single-value context.

在2值上下文中: chanBool, chanInt <- boolInt()得到错误:syntax error: unexpected semicolon or …

channel go goroutine

3
推荐指数
1
解决办法
382
查看次数

在相同的goroutine中创建的goroutine是否始终按顺序执行?

package main

func main() {
        c:=make(chan int)
        for i:=0; i<=100;i++ {
                i:=i
                go func() {
                        c<-i
                }() 
        }   
        for {
                b:=<-c
                println(b)
                if b==100 {
                        break
                }   
        }   
}
Run Code Online (Sandbox Code Playgroud)

上面的代码创建了100个goroutine来插入num到通道c,所以我只是想知道,这些goroutines会以随机顺序执行吗?在我的测试期间,输出将始终为1到100

go goroutine

3
推荐指数
2
解决办法
489
查看次数

Goroutine在http处理程序内执行

如果我在一个http处理程序中启动一个goroutine,它是否会在返回响应后完成?这是一个示例代码:

package main

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

func worker() {
    fmt.Println("worker started")
    time.Sleep(time.Second * 10)
    fmt.Println("worker completed")
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    go worker()
    w.Write([]byte("Hello, World!"))
}

func main() {
    http.HandleFunc("/home", HomeHandler)
    http.ListenAndServe(":8081", nil)
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,workergoroutine是否会在所有情况下完成?或者是否有任何特殊情况无法完成?

http go goroutine

3
推荐指数
2
解决办法
917
查看次数

如何等待一组goroutines?

假设我想开始一组goroutine而不是等待所有这些都完成(例如返回).我可以想到一些基于通道的解决方案(例如创建一个通道并监听它计算收到的消息,这些消息应由每个goroutine发送并在收到相应数量的消息后退出)但是可能有一个更优雅/更有效的解决方案,因为这种情况似乎非常普遍.

concurrency go goroutine

3
推荐指数
1
解决办法
2558
查看次数

Golang goroutine不能使用函数返回值

我希望我可以使用golang执行以下代码:

package main

import (
    "fmt"
    "time"
)

func getA() (int) {

    fmt.Println("getA: Calculating...")
    time.Sleep(300 * time.Millisecond)

    fmt.Println("getA: Done!")
    return 100
}

func getB() (int) {

    fmt.Println("getB: Calculating...")
    time.Sleep(400 * time.Millisecond)

    fmt.Println("getB: Done!")
    return 200
}

func main() {

    A := go getA()
    B := go getB()

    C := A + B // waits till getA() and getB() return
    fmt.Println("Result:", C)
    fmt.Println("All done!")
}
Run Code Online (Sandbox Code Playgroud)

更具体地说,我希望Go可以处理场景背后的并发性.

这可能有点偏离主题,但我很好奇人们对这种隐式并发支持的看法.值得为它付出一些努力吗?什么是潜在的困难和缺点?


编辑:

要明确的是,问题不在于"Go现在正在做什么?",而不是"它是如何实现的?" 虽然我很欣赏@icza的帖子,关于我们应该期待什么,就像现在一样.问题是为什么它不能或不能返回值,以及这样做的潜在复杂性是什么?

回到我的简单示例:

   A := go getA()
   B := go getB()

   C := …
Run Code Online (Sandbox Code Playgroud)

concurrency go goroutine

3
推荐指数
1
解决办法
4182
查看次数

指数超出范围goroutine golang

索引超出范围错误,在for循环生成的goroutine中似乎不可能

这是我正在执行的代码.问题是索引超出范围错误是在对goroutine中countlinks调用的一个参数的评估中产生的.我们正在迭代的切片的长度总是2.基于我对go中的for循环的理解,i永远不应该评估为2(在表达式中产生索引超出范围grph.entryPoints[i]),但它是.拜托,告诉我我是多么疯狂.

func main() {
    grph := structures.ConfigGraphDefault()
    counter := structures.NewCounter()
    queue := structures.NewQueue()
    tracker := structures.NewTracker()
    fmt.Printf("entries: %v\nnodes: %v\n", grph.EntryPoints, grph.Nodes)
    wg := sync.WaitGroup{}
    fmt.Println(len(grph.EntryPoints))
    // this will always evaluate to 2
    l := len(grph.EntryPoints)
    for i := 0; i < l; i++ {
        wg.Add(1)
        go func() {
            fmt.Printf("index: %v, length of slice: %v\n", i, len(grph.EntryPoints))
            structures.CountLinks(&grph, counter, queue, tracker, grph.EntryPoints[i], i)
            wg.Done()
        }()
    }
    wg.Wait()
    fmt.Printf("counter: %v", counter.GetCounts())
}
Run Code Online (Sandbox Code Playgroud)

go goroutine

3
推荐指数
1
解决办法
517
查看次数

使用通道同步多个goroutine

我需要使用单个任务队列和单个结果队列来启动多个工作程序。每个工人都应该在不同的goroutine中启动。我需要等到所有工作人员都将完成并且任务队列将为空后再退出程序。我准备了goroutine同步的小例子。主要思想是我们将排队的任务计数,并等待所有工人完成工作。但是当前的实现有时会遗漏值。为什么会发生这种情况以及如何解决问题?示例代码:

import (
    "fmt"
    "os"
    "os/signal"
    "strconv"
)

const num_workers = 5

type workerChannel chan uint64

// Make channel for tasks
var workCh workerChannel
// Make channel for task counter
var cntChannel chan int

// Task counter
var tskCnt int64

// Worker function
func InitWorker(input workerChannel, result chan string, num int) {
    for {
        select {
        case inp := <-input:
            getTask()
            result <- ("Worker " + strconv.Itoa(num) + ":" + strconv.FormatUint(inp, 10))
        }
    }
}

// Function to manage task …
Run Code Online (Sandbox Code Playgroud)

concurrency synchronization channel go goroutine

3
推荐指数
1
解决办法
1391
查看次数

标签 统计

go ×10

goroutine ×10

channel ×3

concurrency ×3

http ×1

synchronization ×1