Concurrent small case

Applications:

  • Use goroutine and channel to work together
  • 1. Start a writeData coroutine and write 50 integers to the pipeline intChan
  • 2. Start a readData coroutine to read the data written by writeData from the pipeline intChan
  • Note: read and write operations are data in the same pipeline, the main thread needs to wait for the completion of the read and write coroutine before exiting
package main

import "fmt"

// 写入
func write(intChan chan int) {
	for i := 0; i <= 50; i++ {
		intChan <- i
	}
	close(intChan)
}

// 读出
func read(intChan chan int, doneRead chan bool) {

	for {
		val, ok := <-intChan
		if !ok {
			break
		}
		fmt.Println("输出:", val)
	}
	doneRead <- true
}

func main() {
	intChan := make(chan int)
	doneRead := make(chan bool)
	//写入50个整数
	go write(intChan)
	//读出数据
	go read(intChan, doneRead)
	//结束进程
	<-doneRead
	close(doneRead)
	fmt.Println("输出结束")
	return
}

Use defer anonymous function to capture panic

  • demo
defer func(){
    if err:=recover();err!=nil{
        fmt.Println("此方法有panic:",err)
    }
}()
  • Place of application: Apply where you feel or feel that panic will occur

timer timing task

  • Method 1: timer:=time.NewTimer(定时时间)//timing time
  • t:= <-time.C//Automatically send data at the point
  • Method 2: t := <-time.After(定时时间)//Receive data at regular intervals
  • Summary: Method 2 is the encapsulation of Method 1, and the two are internally consistent

Timer pause and reset

  • Pause: timer.Stop()(Must use the method to determine the timed task)
  • Reset:timer.Reset(时间)
package main

import (
	"fmt"
	"math/rand"
	"time"
)

var isStop = isStopTimer()

func main() {
	fmt.Println(time.Now())
	timer := time.NewTicker(time.Second * 3)
	if isStop {
		fmt.Println(<-timer.C)
	} else {
		timer.Stop()
	}
}

func isStopTimer() bool {
	rand.Seed(time.Now().UnixNano())
	tempInt := rand.Intn(4) + 16
	if tempInt >= 18 {
		fmt.Println("找到了")
		return true
	} else {
		return false
	}
}


cycle clock tasks

  • set time formatfmt.Println((<-ticker.C).Format("2006-01-02 03:04:05PM"))
  • 2006-01-02 03:04:05PMThe number cannot be changed, PM is converted to 24
  • Use here:
    • time.NewTicker(时间)Loop to get time points
package main

import (
	"fmt"
	"time"
)

func main() {
	ticker := time.NewTicker(time.Second)
	done := make(chan struct{})//
	go func(done chan struct{}) {
		var count = 0
		for {
			fmt.Println((<-ticker.C).Format("2006-01-02 03:04:05PM"))
			count++
			if count > 2 {
				ticker.Stop()
				done <- struct{}{}//
			}
		}
	}(done)
	<-done//
	fmt.Println("打印结束")
}


Use the task queue to wait for the task to complete

  • Packages used:waitGroup := sync.WaitGroup{}
  • Three main functions:Add(),Done(),Wait()
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	waitGroup := sync.WaitGroup{}
	ticker := time.NewTicker(time.Second)
	waitGroup.Add(1)//
	go func() {
		var count = 0
		for {
			fmt.Println((<-ticker.C).Format("2006-01-02 03:04:05PM"))
			count++
			if count > 2 {
				waitGroup.Done()//
				ticker.Stop()
			}
		}
	}()
	waitGroup.Wait()//
	fmt.Println("打印结束")
}

Guess you like

Origin blog.csdn.net/JUIU9527/article/details/131136243