This is a creation in Article, where the information may have evolved or changed.
Golang Concurrent One
In go, each activity that executes concurrently is called a goroutine. Go has two concurrent programming styles, Communication sequential process mode (channel based), and shared memory.
Creating a goroutine in Go is especially easy, just add the keyword go to the front of the function
func f() { //TODO ADD CODE HERE}func main() { go f()}
Go f () creates a goroutine and concurrently executes the function f
Communication Sequential Process mode
Channel
A channel is a connection between Goroutine and allows one goroutine to send a value to another goroutine. Each channel has a specific type, an int type of channel writing Chan Int.
The channel has three operations: send, receive, close (not commonly used).
The buffer channel has a buffer queue, the receive operation removes an element from the head of the queue, the send operation inserts an element at the end of the queue, and if the queue is full, the send operation is blocked and the queue is empty, then the accept operation is empty.
When the channel capacity is 0 o'clock, the send operation is blocked until another goroutine is received, and the transfer is complete, and two goroutine continue to work. The receiving operation is the same.
code example
Create a Channel
channel := make(chan int)
Create buffer Channel
channel := make(chan struct{},3)
Sending data to a channel
channel <- 1
receiving data from a channel
_ = <- channel
We may need to restrict a function to send only, a function can only receive operations, which can be done by declaring the Chan <-int in the parameter type that this can be sent, the type <-chan int means that only the receive operation can be performed.
Code we implement a producer and consumer example:
func main() { channel := make(chan int, 10) for i := 0; i < 10; i++ { go procedur(channel) } for i := 0; i < 12; i++ { go consumer(channel, i) } for { time.Sleep(time.Second) }}//生产者 只可以进行发送操作func procedur(channel chan<- int) { for i := 0; i < 101; i++ { channel <- i i %= 100 time.Sleep(time.Millisecond * 100) }}//生产者 只可以进行接收操作func consumer(channel <-chan int, id int) { for { v := <-channel fmt.Println(id, v) time.Sleep(time.Millisecond * 200) }}
Imitated the situation of 10 producers and 12 consumers
Select multiplexing
The SELECT statement resembles a switch statement, with a sequence of conditions and an optional default branch, each specifying a communication and associated code block.
Examples of the following forces generating numbers randomly and outputting
channel := make(chan int, 10)for i := 0; i < 100; i++ { select { case v := <-channel: fmt.Println(v) case channel <- i: }}
It is important to note that if multiple conditions are met, select randomly chooses one to execute.