Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to understand goroutine

Shulou Source: shulou.com Published: 2022-06-01 00:54:17 09月17日 Update

How to understand goroutine, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

(1)。 Suppose there is a project that requires three engineering teams to complete, their construction events are independent of each other, who builds quickly and who finishes that part first, and the others do not need to wait for other engineering teams.

Package main

Import (

"fmt"

"time"

)

Func main () {

Fmt.Println ("start construction")

Go workTwo ()

Go workThree ()

Go workOne ()

Fmt.Println ("waiting for the total construction of the project to be completed")

Time.Sleep (time.Second * 3)

}

/ / workOne Engineering team 1 built part of it.

Func workOne () {

WorkTime: = time.Millisecond * 3000 / / time to complete the project

Time.Sleep (workTime)

Fmt.Println ("Construction completed: workOne")

}

/ / workTwo Engineering team 2 built part

Func workTwo () {

WorkTime: = time.Millisecond * 2500 / / time to complete the project

Time.Sleep (workTime)

Fmt.Println ("Construction completed: workTwo")

}

/ / workThree Engineering team 3 built part of it.

Func workThree () {

WorkTime: = time.Millisecond * 2000 / / time to complete the project

Time.Sleep (workTime)

Fmt.Println ("Construction completed: workThree")

}

(2)。 Add acceptance function to the project and use go chan to realize it.

Package main

Import (

"fmt"

"time"

)

Const (

WorkOneDone = "oneDone"

WorkTwoDone = "twoDone"

WorkThreeDone = "threeDone"

)

Func main () {

Fmt.Println ("start construction")

Ch: = make (chan string, 1)

Go func () {

WorkTwo (ch)

} ()

Go func () {

WorkThree (ch)

} ()

Go func () {

WorkOne (ch)

} ()

Go func () {

Test (ch)

} ()

/ / close chan

Defer close (ch)

/ / waiting for the completion of the general project

Time.Sleep (time.Second * 5)

}

Func test (ch chan string) {

For {

Select {

Case v: =

Tags: Engineering engineering team time construction help acceptance clear three events content functions in this regard engineering construction articles novice more knowledge industry information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB OPPO Reno NVidia Microsoft Shulou Information