goroutine

Goroutine execution inside an http handler

半世苍凉 提交于 2019-11-29 11:52:42
If I start a goroutine inside an http handler, is it going to complete even after returning the response ? Here is an example code: 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) } In the above example, is that worker goroutine going to complete in all situations ? Or is there any special case

proper way of waiting for a go routine to finish

老子叫甜甜 提交于 2019-11-29 11:30:35
I wish to know what is the proper way of waiting for a go routine to finish before exiting the program. Reading some other answers it seems that a bool chan will do the trick, as in Playground link 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 } I have two questions here: why the <- done works at all? what happens if I uncomment the last line? I have a deadlock error. Is this because the channel is empty and there is no other function sending values to it? Why the <- done

Solving goroutines deadlock

拟墨画扇 提交于 2019-11-29 08:43:31
I've been trying to solve this simple problem I encountered in Golang concurrency. I've been searching all possible solutions, but found nothing specific to my problem(or I might be missed one). Here's my code: package main import ( "fmt" "time" ) func producer(ch chan int, d time.Duration, num int) { for i:=0; i<num; i++ { ch <- i time.Sleep(d) } } func main() { ch := make(chan int) go producer(ch, 100*time.Millisecond, 2) go producer(ch, 200*time.Millisecond, 5) for { fmt.Println(<-ch) } close(ch) } It prints error: fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan receive

Mutual Exclusion of Concurrent Goroutines

落花浮王杯 提交于 2019-11-29 08:42:33
In my code there are three concurrent routines. I try to give a brief overview of my code, Routine 1 { do something *Send int to Routine 2 Send int to Routine 3 Print Something Print Something* do something } Routine 2 { do something *Send int to Routine 1 Send int to Routine 3 Print Something Print Something* do something } Routine 3 { do something *Send int to Routine 1 Send int to Routine 2 Print Something Print Something* do something } main { routine1 routine2 routine3 } I want that, while codes between two do something (codes between two star marks) is executing, flow of control must not

Go, tcp too many open files debug

女生的网名这么多〃 提交于 2019-11-29 03:40:16
Here's a straightforward Go http (tcp) connection test script func main() { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") })) defer ts.Close() var wg sync.WaitGroup for i := 0; i < 2000; i++ { wg.Add(1) go func(i int) { defer wg.Done() resp, err := http.Get(ts.URL) if err != nil { panic(err) } greeting, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { panic(err) } fmt.Printf("%s", i, greeting) }(i) } wg.Wait() } And If I run this in Ubuntu I get: panic: Get http://127.0.0.1:33202: dial tcp 127.0.0.1

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

吃可爱长大的小学妹 提交于 2019-11-28 23:02:49
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? 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, hopefully. This is an instance of a more universal Go documentation rule: Things are not safe for concurrent

Go project's main goroutine sleep forever?

∥☆過路亽.° 提交于 2019-11-28 21:21:39
Is there any API to let the main goroutine sleep forever? In other words, I want my project always run except when I stop it. "Sleeping" You can use numerous constructs that block forever without "eating" up your CPU. For example a select without any case (and no default ): select{} Or receiving from a channel where nobody sends anything: <-make(chan int) Or receiving from a nil channel also blocks forever: <-(chan int)(nil) Or sending on a nil channel also blocks forever: (chan int)(nil) <- 0 Or locking an already locked sync.Mutex : mux := sync.Mutex{} mux.Lock() mux.Lock() Quitting If you

Why is time.sleep required to run certain goroutines?

浪尽此生 提交于 2019-11-28 19:13:53
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" written to the screen five times. What is so important about time.Sleep that saves the goroutine from dying?

Is a Go goroutine a coroutine?

喜欢而已 提交于 2019-11-28 15:47:27
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. K Z 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—onto a set of threads. When a coroutine blocks, such as by calling a blocking system call, the run

How do goroutines work? (or: goroutines and OS threads relation)

坚强是说给别人听的谎言 提交于 2019-11-28 15:38:51
How can other goroutines keep executing whilst invoking a syscall? (when using GOMAXPROCS=1) As far as I'm aware of, when invoking a syscall the thread gives up control until the syscall returns. How can Go achieve this concurrency without creating a system thread per blocking-on-syscall goroutine? From the documentation : Goroutines They're called goroutines because the existing terms—threads, coroutines, processes, and so on—convey inaccurate connotations. A goroutine has a simple model: it is a function executing concurrently with other goroutines in the same address space. It is