Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to understand Goroutine in Golang

Shulou Source: shulou.com Published: 2022-06-01 00:53:50 09月12日 Update

Golang in the Goroutine how to understand, 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.

What is Go Cooperative Program?

Go Goroutine is a function that runs at the same time as other functions. You can think of the Go protocol as a lightweight thread managed by the Go runtime.

Add the go keyword before the function call, and the call will be executed concurrently in a new goroutine. The goroutine also ends automatically when the called function returns. Sounds like Task in C #.

It is important to note that if the function has a return value, the return value will be discarded.

Go protocols (Goroutine) communicate with each other through a channel (channel), which is simply a channel for communication between multiple protocols. Channel can prevent resource contention when multiple co-programs access shared memory.

How to use package main

Import ("fmt"time")

Func hello () {fmt.Println ("Hello world goroutine")} func main () {go hello () time.Sleep (1 * time.Second) fmt.Println ("main function")} Channel (pipe)

Channel (pipe) can be thought of as a channel for communication between co-programs. Just as water flows from one end of the pipe to the other, data can be sent from one end of the channel and received at the other end.

1. Define

Every channel has a type. This type is the data type that allows channel transmission. Channel is type dependent, and a channel can only pass a value of one type, which needs to be specified when declaring channel.

two。 Statement

a. We need to create a channel through the built-in function make.

The following code declares a channel:

Var ch chan int

b. Like other variable definitions, quick declaration is an effective and concise way to define channels:

A: = make (chan int)

c. Create a buffered channel

C: = make (chan int, 1024)

/ / read data for i:=range c {...} from buffered channel

3. Send and receive data

The syntax for sending and receiving data over a channel is as follows:

Data: =

Tags: Channel data function type pipe one end between code communication example multiple machine language help buffer compile run clear concise elegant Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB OPPO Reno Microsoft Docker Apple