The Foundation of Go Language: Channel

Shared memory through communication (Java communicates through shared memory)

Definition
func service() string {
	time.Sleep(time.Millisecond * 50)
	return "Done"
}

func AsyncService() chan string {
	retCh := make(chan string, 1)//Create a channel with a capacity of 1 element and a type of string
	go func() {
		ret := service()
		fmt.Println("returned result.")
		retCh <- ret//Put the value in channel retCh
		fmt.Println("service exited.")
	}()
	return retCh
}

func TestAsynService(t *testing.T) {
	retCh := AsyncService()
	otherTask()
	fmt.Println(<-retCh)//Remove a value from channel retCh
	time.Sleep(time.Second * 1)
}

Channel creation grammar: make(chan element type, capacity), capacity is an optional value referring to the maximum number of element values that can be cached by the channel, which cannot be negative.

When the capacity is 0, it is called Non-buffer channel, and when it is larger than 0, it is called buffer channel.

Channel is a queue, following the first in first out principle

Receiving operators are required for sending and receiving element values<-

It is not the element to the right of the acceptance operator that enters the channel, but a copy of it.

Buffer channel:

Non-buffer channel:

Multichannel Selection
func TestSelect(t *testing.T) {
	select {
	case ret := <-retCh1://Execute when there is data in channel retCh1
		t.Log(ret)
	case ret := <-retCh2://Execute when there is data in channel retCh2
		t.Error("time out")
    //When default does not exist retCh1 retCh2 has no data, the consortium will be blocked.
    default://Execute when channel retCh1 and retCh2 have no data
        t.Error("error")
	}
}
Realization of Channel Timeout Control
select {
case ret := <-retCh:
    t.Log(ret)
case <-time.After(time.Second * 1): //Setting timeout time
    t.Error("time out")
}
Closing channel

Sending data to closed channels will lead to panic, and closing closed channels will also lead to panic.

Receiving operation can sense channel closure and exit safely.

V, ok<-ch; OK is bool value, true is normal acceptance, false is channel closed

All channel receivers return immediately from the blocking wait when the channel is closed and the ok value is false. This broadcast mechanism is often used to send signals to multiple subscribers at the same time. For example: exit signal.

channel closure principle:

(1) Who creates the channel and who is responsible for closing it (2) Do not close channel with sender (3) channel as a function parameter has the best direction

Code:

package channel_close

import (
	"fmt"
	"sync"
	"testing"
)

//Producer
func dataProducer(ch chan int, wg *sync.WaitGroup) {
	go func() {
		for i := 0; i < 10; i++ {
			ch <- i
		}
		close(ch)

		wg.Done()
	}()

}

//Recipient
func dataReceiver(ch chan int, wg *sync.WaitGroup) {
	go func() {
		for {
			if data, ok := <-ch; ok {
				fmt.Println(data)
			} else {
				break
			}
		}
		wg.Done()
	}()

}

func TestCloseChannel(t *testing.T) {
	var wg sync.WaitGroup
	ch := make(chan int)
	wg.Add(1)
	dataProducer(ch, &wg)
	wg.Add(1)
	dataReceiver(ch, &wg)
	wg.Wait()

}

Context

· Root Context: Created through context.Background 0·

SubContext: context. WithCancel (parentContext) creation

ctx, cancel := context.WithCancel(context.Background))

When the Context is cancelled, its sub-contexts will be cancelled.

· Receiving Cancellation Notification <-ctx.Done()

Advanced usage of channels

The channels we mentioned before are both two-way, that is, the channels that can be sent or received; the so-called single channel means that only the hair and seat can be received.

Single channel definition:

//Send Channel (Only Send Can't Receive)
var uselessChan = make(chan<- int, 1)

//Receiving Channel (Receiving Only, Not Sending)
var uselessChan1 = make(<-chan  int, 1)

Channels are used to transfer data, while single channels cannot transfer data.

****** Code words are not easy. If they are helpful to you, please pay attention to them.

******** Love Technology Love Life QQ Group: 894109590****

Keywords: Programming Java

Added by Crowly on Wed, 21 Aug 2019 13:02:55 +0300