SoFunction
Updated on 2025-03-05

GO language coroutine creation and use and solve resource competition through channel

Create a coroutine

goroutine is the core of go design, which is coroutine
The main coroutine has terminated, and the child coroutine has terminated.

package main
import (
	"fmt"
	"time"
)
func newTask() {
	for {
		("this is a newTask")
		() //Delay 1s	}
}
func main() {
	go newTask() //Create a new coroutine and create a new task	for {
		("this is a main goroutine")
		() //Delay 1s	}
}

The main coroutine terminates, and the child coroutine terminates.

package main
import (
	"fmt"
	"time"
)
//The main coroutine exits, and other sub coroutines must also exitfunc main() {
	go func() {
		i := 0
		for {
			i++
			("Subcorrelations i = ", i)
			()
		}
	}() //Don't forget ()	i := 0
	for {
		i++
		("main i = ", i)
		()
		if i == 2 {
			break
		}
	}
}

runtime package

Gosched gives up CPU time slices

Wait for other coroutines to complete

() is used to give up the CPU time slice, give up the execution permission of the current goroutine (coroutine), the scheduler arranges other waiting tasks to run, and resumes execution from this location some time next time.
Similar: Relay race, A runs for a while and encounters code() and handes the baton to B, A rests, B continues to run

Case:

package main
import (
	"fmt"
	"runtime"
)
func main() {
	go func() {
		for i := 0; i < 5; i++ {
			("go")
		}
	}()
	for i := 0; i < 2; i++ {
		//Give up the time slice, let other protocols be executed first, it will be executed, and then come back to execute this coroutine		() 
		("hello")
	}
}


go
go
go
go
go
hello
hello

Goexit ends the current coroutine immediately

()  //End the current coroutine immediately

Case:

package main
import (
	"fmt"
	"runtime"
)
func test() {
	defer ("ccccccccccccc")
	//return //terminate this function	() // Terminate the coroutine	("dddddddddddddddddddddd")
}
func main() {
	//Create a new coroutine	go func() {
		("aaaaaaaaaaaaaaaaaa")

		//Another function was called		test()
		("bbbbbbbbbbbbbbbbbbb")
	}() //Don't forget ()	//Written a dead loop specifically to prevent the main coroutine from ending	for {
	}
}
aaaaaaaaaaaaaaaaaa
ccccccccccccc

GOMAXPROCS sets the maximum number of parallel CPU cores and returns the previous value

() //Set the maximum number of parallel CPU cores and return the previous value
package main
import (
	"fmt"
	"runtime"
)
func main() {
	//n := (1) //Specify operation with 1 core	n := (2) //Specify the operation with 8 cores	("n = ", n)
	for {
		go (1)
		(0)
	}
}

() Get the number of goroutines currently running

Let me first introduce the simplest monitoring method.

Get the number of goroutines currently running through () and use it to confirm whether a leak has occurred.

func main() {
 go test()
 go test()
 go test()
 go test()
 a:=()
 (a) // 5
 for  {
 }
}

Multitasking resource competition problem

package main
import (
	"fmt"
	"time"
)
//Define a printer, the parameters are strings, print them according to each character//The printer is a public resourcefunc Printer(str string) {
	for _, data := range str {
		("%c", data)
		()
	}
	("\n")
}
func person1() {
	Printer("hello")
}
func person2() {
	Printer("world")
}
func main() {
	// Create 2 new coroutines, representing 2 people, and 2 people use the printer at the same time	go person1()
	go person2()
	//Specially not allow the main coroutine to end, the dead loop	for {
	}
}

Solve resource competition issues through channel

package main
import (
	"fmt"
	"time"
)
//Global variable, create a channelvar ch = make(chan int)
//Define a printer, the parameters are strings, print them according to each character//The printer is a public resourcefunc Printer(str string) {
	for _, data := range str {
		("%c", data)
		()
	}
	("\n")
}
//Only after person1 is executed, you can go to person2 to executefunc person1() {
	Printer("hello")
	ch <- 666 //Write data to the pipeline and send}
func person2() {
	<-ch //Get data from the pipeline and receive it. If the channel has no data, it will block	Printer("world")
}
func main() {
	// Create 2 new coroutines, representing 2 people, and 2 people use the printer at the same time	go person1()
	go person2()
	//Specially not allow the main coroutine to end, the dead loop	for {
	}
}

How to wait until the remaining coroutines are finished before exiting

var wg 
(2)  //Number of tasks() //Finish() //waitpackage main
import (
	"fmt"
	"sync"
)
var wg 
func main() {
	(2)
	out := producer()
	consumer(out)
	defer ("Main thread ends")
	()  //wait}
//This channel can only be written, not readfunc producer() chan interface{} {
	ch := make(chan interface{})
	go func() {
		for i := 0; i < 5; i++ {
			ch <- ("Coprogram 1-%d", i) //Write string		}
		defer close(ch)
		()  //Finish	}()
	return ch
}
//This channel can only be read, not writtenfunc consumer(data chan interface{}) {
	defer ("Read End")
	go func() {
		for num := range data {
			(num)
		}
		() //Finish	}()
}

The above is the detailed content of creating and using GO language coroutines and solving resource competition through channel. For more information about GO language coroutines and channel solving resource competition, please pay attention to my other related articles!