goroutine

Close multiple goroutine if an error occurs in one in go

北城余情 提交于 2019-11-27 14:47:07
consider this function : func doAllWork() error { var wg sync.WaitGroup wg.Add(3) for i := 0; i < 2; i++ { go func() { defer wg.Done() for j := 0; j < 10; j++ { result, err := work(j) if err != nil { // can't use `return err` here // what sould I put instead ? os.Exit(0) } } }() } wg.Wait() return nil } In each goroutine, the function work() is called 10 times. If one call to work() returns an error in any of the running goroutines, I want all the goroutines to stop immediately, and the program to exit. Is it ok to use os.Exit() here ? How should I handle this ? Edit : this question is

Can I concurrently write different slice elements

随声附和 提交于 2019-11-27 14:41:18
I have a slice that contains work to be done, and a slice that will contain the results when everything is done. The following is a sketch of my general process: var results = make([]Result, len(jobs)) wg := sync.WaitGroup{} for i, job := range jobs { wg.Add(1) go func(i int, j job) { defer wg.Done() var r Result = doWork(j) results[i] = r }(i, job) } wg.Wait() // Use results It seems to work, but I have not tested it thoroughly and am not sure if it is safe to do. Generally I would not feel good letting multiple goroutines write to anything , but in this case, each goroutine is limited to its

Is it safe for more than one goroutine to print to stdout?

拈花ヽ惹草 提交于 2019-11-27 14:31:21
问题 I have multiple goroutines in my program, each of which makes calls to fmt.Println without any explicit synchronization. Is this safe (i.e., will each line appear separately without data corruption), or do I need to create another goroutine with synchronization specifically to handle printing? 回答1: No it's not safe even though you may not sometimes observe any troubles. IIRC, the fmt package tries to be on the safe side, so probably intermixing of some sort may occur but no process crash,

Why is time.sleep required to run certain goroutines?

荒凉一梦 提交于 2019-11-27 12:06:02
问题 In the GO tutorial, we have this slide: Goroutines 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") } Running this code produces expected results ("world" and "hello" written to the screen interchangeably 5 times). However, if we comment out time.Sleep (and consequently, the "time" line of the import) and run the program again, we are left with only "hello"

Golang : anonymous struct and empty struct

你说的曾经没有我的故事 提交于 2019-11-27 11:15:13
http://play.golang.org/p/vhaKi5uVmm package main import "fmt" var battle = make(chan string) func warrior(name string, done chan struct{}) { select { case opponent := <-battle: fmt.Printf("%s beat %s\n", name, opponent) case battle <- name: // I lost :-( } done <- struct{}{} } func main() { done := make(chan struct{}) langs := []string{"Go", "C", "C++", "Java", "Perl", "Python"} for _, l := range langs { go warrior(l, done) } for _ = range langs { <-done } } [1st Question] done <- struct{}{} How and Why do we need this weird-looking struct? Is it empty struct or anonymous struct? I googled it

Is a Go goroutine a coroutine?

こ雲淡風輕ζ 提交于 2019-11-27 09:32:00
问题 In the Google I/O 2012 presentation Go Concurrency Patterns, Rob Pike mentions that several goroutines can live in one thread. Does this imply that they are implemented as coroutines? If not, how they are implemented? Links to source code would be welcome. 回答1: Not quite. The Go FAQ section Why goroutines instead of threads? explains: Goroutines are part of making concurrency easy to use. The idea, which has been around for a while, is to multiplex independently executing functions—coroutines

Prevent the main() function from terminating before goroutines finish in Golang

主宰稳场 提交于 2019-11-27 09:28:57
Have loook at this contrived example: package main import "fmt" func printElo() { fmt.Printf("Elo\n") } func printHello() { fmt.Printf("Hello\n") } func main() { fmt.Printf("This will print.") i := 0 for i < 10 { go printElo() go printHello() i++ } } The output of this program would be just "This will print". Output of goroutines printElo() and printHello will not be emitted because, I guess, the main() function thread will finish before the goroutines have a chance to even start executing. What is the idiomatic way to make similar code work in Golang and not terminate prematurely? Simplest,

golang struct concurrent read and write without Lock is also running ok?

孤者浪人 提交于 2019-11-27 07:11:32
问题 concurrentMap() function Have WARNING: DATA RACE , And fatal error : concurrent map read and map write concurrentStruct() have WARNING: DATA RACE, But running ok why the struct can DATA RACE? package main import ( "sync" ) func main() { // concurrentMap() concurrentStruct() // concurrentStructWithMuLock() } type Metadata struct { mu sync.RWMutex // 🔐 key bool } // concurrentStruct 并发操作结构体 // concurrent read and write the struct // go run -race main.go 有 WARNING: DATA RACE,但是可以运行 // go run

How would you define a pool of goroutines to be executed at once in Golang?

不打扰是莪最后的温柔 提交于 2019-11-27 05:52:40
TL;TR: Please just go to the last part and tell me how you would solve this problem. I've begun using Golang this morning coming from Python. I want to call a closed-source executable from Go several times, with a bit of concurrency, with different command line arguments. My resulting code is working just well but I'd like to get your input in order to improve it. Since I'm at an early learning stage, I'll also explain my workflow. For the sake of simplicity, assume here that this "external closed-source program" is zenity , a Linux command line tool that can display graphical message boxes

go routine blocking the others one [duplicate]

大城市里の小女人 提交于 2019-11-27 03:50:40
问题 This question already has answers here : Why is this Go code blocking? (3 answers) Closed 2 years ago . The following code run forever instead of stopping one second after the beginning. The go routine with the infinite loop seems to prevent the other one from sending to the timeout channel. Is that normal ? func main(){ timeout:=make(chan int) go func(){ time.SLeep(time.Second) timeout<-1 }() res:=make(chan int) go func(){ for{ } res<-1 }() select{ case<-timeout: fmt.Println("timeout") case<