This is the 14th day of my participation in the August Text Challenge.More challenges in August

Goroutine

A lightweight thread that runs in user mode, called a tasklet or coroutine.

Coroutines perform more efficiently than threads and processes. No overhead of thread and process switching.

When the Go program starts, the main function also runs in a goroutine, called main Goroutine

Whenever a function is called with go, a new Goroutine is created

The creation of a goroutine

func sayHi() { for i := 0; i < 100; I ++ {ftt. Println(" I am a goroutine, ", I)}} // A Goroutine must correspond to a function, multiple Goroutines can perform the same function // So far, we have learned go sayHi() fmt.println (" I am the main function, I'm done ") // When main is finished, the unfinished Goroutine also stops executing // For example, when sayHi is halfway through execution, // We can choose to let main Goroutine exit a little later to allow other goroutine to finish time.sleep (time.microsecond * 1000).Copy the code

sync.WaitGroup

Var wg sync.waitgroup func sayHi() {FMT.Println(" I am sayHi, I am executing ") for I := 0; i < 100; I ++ {fmt.Println(" I am a goroutine, ", I)} Wg.done ()} wg.done ()} wg.done ()} wg.done () {wg.done ()} Wg.add (1) go sayHi() // When no goroutine is running in the waitGroup, Wg.wait () fmt.println (" I'm main, I'm done ")Copy the code

Open multiple Goroutines

Var wg sync.WaitGroup var count int sayHello(I int) {count++ FMT.Println(" sayHello, I am a goroutine, ", i) wg.Done() } wg.Add(20) for i := 0; i < 20; I ++ {go sayHello(I)} wg.wait () fmt.println (" sayHello: ", count, "time ") fmt.println (" I'm main, I'm done ")Copy the code

Goroutine anonymous function

/* wg.Add(20) for i := 0; i < 20; I ++ {// an anonymous function is used to capture the external variable go func() {// multiple duplicate values are present when printing I. ", i) wg.Done() }() } */ wg.Add(20) for i := 0; i < 20; Go func(I int) {FMT.Println(" I am an anonymous function: ", I) wg.done ()}(I)} wg.wait () fmt.println (" I'm main, I'm Done ")Copy the code

GOMAXPROCS

func func1() { for i := 0; i < 100; I ++ {FMT.Println(" FUNC1, ", I)}} func func2() {for I := 0; i < 100; I ++ {FMT.Println(" FUNC2, ", I)}} func func3() {for I := 0; i < 100; I ++ {FMT.Println(" I am func3, ", I)}} // Specifies how many system-state threads are used to execute the goroutine. // When more than one CPU executes a Goroutine, We can see multiple Goroutines swapped on the console printout runtime.GOMAXPROCS(3) go func1() go func2() go func3() FMT.Println(" I am the main function, ") time.sleep (time.second)Copy the code

conclusion

Goroutine is a lightweight thread. The management of Goroutine is unified by the scheduler implemented by GO.

Goroutine has a many-to-many relationship with threads in the system, and we don’t care how they are scheduled.

You can focus more on writing business functions, and Golang naturally supports concurrent programming!!