Home >Backend Development >Golang >How to create a shared memory Goroutine in Go?
Goroutine of shared memory can be implemented through channel: create a channel to specify the element type. Start a Goroutine to write data to the channel. Use a range loop in the main Goroutine to read data from the channel. Completion of the write is indicated by closing the channel.
#How to create a shared memory Goroutine in Go?
In Go, shared memory is implemented through channels. A channel is essentially a first-in-first-out (FIFO) queue for sending and receiving values between Goroutines.
Practical case
Creating a shared memory Goroutine is very simple. The following is sample code:
package main import ( "fmt" "sync" ) func main() { // 创建一个 channel ch := make(chan int) // 创建 Goroutine 并启动,它将向 channel 写入数据 var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() for i := 0; i < 10; i++ { ch <- i } // 关闭 channel 表示完成 close(ch) }() // 从 channel 中读取数据 for v := range ch { fmt.Println(v) } wg.Wait() }
Explanation
int
). The go
statement starts a new Goroutine and passes a function as a parameter. close(ch)
to close the channel. By using channels for shared memory, we can safely transfer data between Goroutines.
The above is the detailed content of How to create a shared memory Goroutine in Go?. For more information, please follow other related articles on the PHP Chinese website!