Home >Backend Development >Golang >How to create a shared memory Goroutine in Go?

How to create a shared memory Goroutine in Go?

WBOY
WBOYOriginal
2024-06-02 11:32:571002browse

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.

如何在 Go 中创建一个共享内存的 Goroutine?

#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

  • When creating a channel, you need to specify its element type (in this case int). The
  • go statement starts a new Goroutine and passes a function as a parameter.
  • In Goroutine, we use a for loop to write data to the channel.
  • When the Goroutine is completed, you can use close(ch) to close the channel.
  • In the main Goroutine, we use a range loop to read data from the channel. The range loop will not exit until the channel is closed.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn