??
直接上代码:
1. 第一种情况, 如果没有select{}, main 主线程不会等待coroutine运行,导致coroutine得不到机会运行。
You are requesting eventual scheduling (using the two go statements) of two goroutines and then you exit main without giving the scheduler a chance to do anything.
有了select, 程序正常运行。
[plain]
view plain
copy
print
?
- packagemain
- import(
- "fmt"
- "time"
- )
- funcmain(){
- gofunc1()
- gofunc2()
- select{}
- }
- funcfunc1(){
- for{
- fmt.Println("here1")
- time.Sleep(10*time.Minute)
- }
- }
- funcfunc2(){
- for{
- fmt.Println("here2")
- time.Sleep(10*time.Minute)
- }
package main
import (
"fmt"
"time"
)
func main() {
go func1()
go func2()
select{}
}
func func1() {
for{
fmt.Println("here1")
time.Sleep(10 * time.Minute)
}
}
func func2() {
for{
fmt.Println("here2")
time.Sleep(10 * time.Minute)
} }
2. coroutine有机会运行,但是会发生死锁,fatal error: all goroutines are asleep - deadlock!
The goroutine executing func1 exited,ditto for func2. The maingoroutine is blocked with no hope to recover while no other goroutinecan be scheduled.
[plain]
view plain
copy
print
?
- packagemain
- import(
- "fmt"
- //"time"
- )
- funcmain(){
- gofunc1()
- gofunc2()
- select{
- }
- }
- funcfunc1(){
- fmt.Println("here1")
- }
- funcfunc2(){
- fmt.Println("here2")
- }
package main
import (
"fmt"
//"time"
)
func main() {
go func1()
go func2()
select {
}
}
func func1() {
fmt.Println("here1")
}
func func2() {
fmt.Println("here2")
}
3. 第三种情况, 正常运行。
[plain]
view plain
copy
print
?
- packagemain
- import(
- "fmt"
- )
- varc=make(chanint,2)
- funcmain(){
- gofunc1()
- gofunc2()
- <-c
- <-c
- fmt.Println("ok")
- }
- funcfunc1(){
- fmt.Println("here1")
- c<-1
- }
- funcfunc2(){
- fmt.Println("here2")
- c<-1
- }
package main
import (
"fmt"
)
var c = make(chan int,2)
func main() {
go func1()
go func2()
<-c
<-c
fmt.Println("ok")
}
func func1() {
fmt.Println("here1")
c <- 1
}
func func2() {
fmt.Println("here2")
c <- 1
}
4. 实现上面的目的的另外一种方法:
[plain]
view plain
copy
print
?
- varwgsync.WaitGroup
- varurls=[]string{
- "http://www.golang.org/",
- "http://www.google.com/",
- "http://www.somestupidname.com/",
- }
- for_,url:=rangeurls{
- //IncrementtheWaitGroupcounter.
- wg.Add(1)
- //LaunchagoroutinetofetchtheURL.
- gofunc(urlstring){
- //Decrementthecounterwhenthegoroutinecompletes.
- deferwg.Done()
- //FetchtheURL.
- http.Get(url)
- }(url)
- }
- //WaitforallHTTPfetchestocomplete.
- wg.Wait()
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|