标签: goroutine

这个陈怎么泄露了?

我想了解这张幻灯片中列出的问题:

http://talks.golang.org/2013/bestpractices.slide#27

在URL死亡时复制代码:

func sendMsg(msg, addr string) error {
    conn, err := net.Dial("tcp", addr)
    if err != nil {
        return err
    }
    defer conn.Close()
    _, err = fmt.Fprint(conn, msg)
    return err
}

func broadcastMsg(msg string, addrs []string) error {
    errc := make(chan error)
    for _, addr := range addrs {
        go func(addr string) {
            errc <- sendMsg(msg, addr)
            fmt.Println("done")
        }(addr)
    }

    for _ = range addrs {
        if err := <-errc; err != nil {
            return err
        }
    }
    return …
Run Code Online (Sandbox Code Playgroud)

concurrency go garbage goroutine

5
推荐指数
1
解决办法
143
查看次数

有没有办法将for循环作为go例程运行而不将其放在单独的func中

假设我想设置一个for循环但不想阻止执行,显然我可以将for循环放在一个函数中f并调用go f并继续我的生活,
但我很好奇是否有办法go for直接调用, 就像是:

fmt.Println("We are doing something")
//line below is my question
go for i := 1; i < 10; i ++ {
    fmt.Println("stuff running in background")
} 
// life goes on
fmt.Println("c'est la vie")
Run Code Online (Sandbox Code Playgroud)

for-loop go goroutine

5
推荐指数
2
解决办法
3208
查看次数

Golang http server 在启动无限循环的goroutine时阻塞

正如我从 golang 文档中了解到的,如果我将 runtime.GOMAXPROCS(8) 设置为 8 核(intel i7)的 cpu,然后启动一个无限循环的 goroutine,其他 gorutines 不应该被阻塞,因为有足够的线程和 goprocs。但是在使用 net/http 包时就不是这样了,一个无限循环的 goroutine 会在几次调用后阻塞 http 服务器。任何人都可以帮助解释原因吗?

  1. 如果我注释“无限循环”这一行,在服务器之后启动客户端,客户端将输出1000个星号;但是如果我启用 goroutine,客户端会在打印几个星号后阻塞
  2. 我已经尝试在 goroutine 中添加 runtime.LockOSThread() ,似乎不起作用
  3. 我的环境:osx 10.10, go version go1.3.1 darwin/amd64

服务器代码:

package main

import (
    "fmt"
    "log"
    "net/http"
    "runtime"
)

func myHandler(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("hello"))
}

func infiniteloop() {
    for {

    }
}

func main() {
    // set max procs for multi-thread executing
    runtime.GOMAXPROCS(runtime.NumCPU())

    // print GOMAXPROCS=8 on my computer
    fmt.Println("GOMAXPROCS=", runtime.GOMAXPROCS(-1))
    http.Handle("/", http.HandlerFunc(myHandler))

    // uncomment …
Run Code Online (Sandbox Code Playgroud)

http block go goroutine

5
推荐指数
1
解决办法
2795
查看次数

为什么不读取/写入其内容的结构的方法仍会导致竞争情况?

从戴夫·切尼博客,下面的代码显然会导致比赛的情况下仅通过改变来解决func (RPC) version() int到func (*RPC) version() int:

package main

import (
        "fmt"
        "time"
)

type RPC struct {
        result int
        done   chan struct{}
}

func (rpc *RPC) compute() {
        time.Sleep(time.Second) // strenuous computation intensifies
        rpc.result = 42
        close(rpc.done)
}

func (RPC) version() int {
        return 1 // never going to need to change this
}

func main() {
        rpc := &RPC{done: make(chan struct{})}

        go rpc.compute()         // kick off computation in the background
        version := …
Run Code Online (Sandbox Code Playgroud)

concurrency struct go race-condition goroutine

5
推荐指数
1
解决办法
77
查看次数

多次取消 context.Context 吗?

我正在开发一个控制台音乐播放器Go。每当用户选择并播放专辑时,我都会启动一个 goroutine来循环播放列表。

playlist := make([]*Media, 0)
for _, path := range album.Paths {
    media, err := NewMediaFromPath(path)
    // return err

    playlist = append(playlist, media)
}

for idx := range playlist {
    player.SetMedia(playlist[idx])
    err = player.Play()
    // check err

    status, err := player.MediaState()
    // check err

    for status != MediaEnded && status != MediaStopped {
        // update UI and check player status
        // loop until the song finishes
        status, err = player.MediaState()
    }
}
Run Code Online (Sandbox Code Playgroud)

当用户 …

tui go goroutine cancellation

5
推荐指数
1
解决办法
8222
查看次数

Go 通道与 JavaScript 生成器有何不同?

Go 通道可用于在 goroutine 之间进行通信。类似地,yield 和 next 语法可用于在两个生成器之间进行通信。我的假设正确吗?如果不是,我哪里错了?

javascript generator go goroutine node.js

5
推荐指数
1
解决办法
753
查看次数

Go运行时如何检查goroutine是否被阻塞?

Go 文档说:

当协程阻塞时,例如通过调用阻塞系统调用,运行时会自动将同一操作系统线程上的其他协程移动到不同的可运行线程,这样它们就不会被阻塞

但是运行时如何检测 goroutine 被阻塞呢?

例如,如果我将在 go-routine 之一中运行计算,它会被评估为阻塞操作吗?

package main

import (
    "fmt"
    "runtime"
)

func f(from string, score int) {
    for i := 0; i < score; i++ {
            for z := 0; z < score; z++ {
        }
    }

    fmt.Println(from, " Done")
}   

func main() {
runtime.GOMAXPROCS(1)
f("direct", 300000)
go f("foo", 200000)
go f("bar", 20000)
go f("baz", 2000)

 go func(msg string) {
        fmt.Println(msg)
    }("going without loop")

       var input string
    fmt.Scanln(&input)
    fmt.Println("done")
}
Run Code Online (Sandbox Code Playgroud)

我得到的结果是:baz,boo bar。但为什么?Go 知道这foo是阻塞吗?

concurrency go goroutine

5
推荐指数
1
解决办法
3469
查看次数

Goroutine执行顺序

我是golang的初学者,正在学习goroutine和channel。直观上,我认为golang中的goroutine本质上是一个独立运行的线程。因此,如果有多个goroutine,执行顺序就无法保证。因此,以下代码应以随机顺序输出“ping”和“pong”。然而,我观察到该程序依次产生“ping”和“pong”。谁能为我解释一下原因吗?任何回复都会有帮助。谢谢!

我发现的另一个有趣的观察是,如果我不在打印机函数内调用 sleep 函数,程序将以随机顺序输出。

package main

import (
  "fmt"
  "time"
)

func pinger(c chan string) {
  for i := 0; ; i++ {
    c <- "ping"
  }
}

func printer(c chan string) {
  for {
    msg := <- c
    fmt.Println(msg)
    time.Sleep(time.Second * 1)
  }
}

func ponger(c chan string) {
  for i := 0; ; i++ {
    c <- "pong"
  }
}

func main() {
  var c chan string = make(chan string)

  go pinger(c)
  go ponger(c)
  go printer(c)

  var input …
Run Code Online (Sandbox Code Playgroud)

concurrency go goroutine

5
推荐指数
1
解决办法
1150
查看次数

Go 例程中基于上下文的长时间运行循环的终止

我正在实现一个功能,需要定期从目录中读取文件、解析它们并将其导出到 REST 服务。作为同一部分,我想优雅地处理程序终止(SIGKILL、SIGQUIT 等)。同样,我想知道如何实现基于上下文的进程取消。

为了定期执行流程,我使用 gocron。

cmd/scheduler.go

func scheduleTask(){
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    s := gocron.NewScheduler()
    s.Every(10).Minutes().Do(processTask, ctx)
    s.RunAll()  // run immediate
    <-s.Start() // schedule
    for {
        select {
        case <-(ctx).Done():
            fmt.Print("context done")
            s.Remove(processTask)
            s.Clear()
            cancel()
        default:
        }
    }
}   
func processTask(ctx *context.Context){
  task.Export(ctx)
}
Run Code Online (Sandbox Code Playgroud)

任务/export.go

func Export(ctx *context.Context){
   pendingFiles, err := filepath.Glob("/tmp/pending/" + "*_task.json")
   //error handling
   //as there can be 100s of files, I would like to break the loop when context.Done() to return asap & clean …
Run Code Online (Sandbox Code Playgroud)

go goroutine

5
推荐指数
1
解决办法
5252
查看次数

当主/父 Goroutine 退出或返回时,未完成的 Goroutine 会发生什么?

我正在阅读Go编程语言书,第8.4章中有这个例子

func mirroredQuery() string{
    responses := make(chan string, 3)
    go func() { responses <- request("asia.gopl.io") }()
    go func() { responses <- request("americas.gopl.io") }()
    go func() { responses <- request("europe.gopl.io") }()
    return <- responses // return the quickest response
}
Run Code Online (Sandbox Code Playgroud)

还有这样的评论

如果我们使用无缓冲的通道,两个速度较慢的 goroutine 会在尝试将其响应发送到没有 goroutine 接收的通道时陷入困境。

这个评论本身就有道理。mirroredQuery但是,当在缓冲情况下返回时,两个慢速 goroutine 会发生什么情况呢?他们是否仍然跑完或被取消?

编辑:我知道如果主 gorountine 退出,那么 2 个较慢的 gorountine 将“蒸发”,无论它们是否正在运行。但是,如果主 goroutine 仍在运行,mirroredQuery()并且已经返回,那么 2 个慢速 goroutine 会运行到最后吗?基本上退货responses后还存在吗mirroredQuery?如果是这样,那么原则上这两个慢协程似乎可以完成;如果不是,那么我们仍然像无缓冲的情况一样存在泄漏吗?

go goroutine

5
推荐指数
1
解决办法
3405
查看次数