0


慕课网Go-4.package、单元测试、并发编程

package

在这里插入图片描述

1_1_User.go

package user

type User struct{
    Name string}

1_1_UserGet.go

package user

funcGetCourse(c User)string{return c.Name
}

1_1_UserMain.go

package main

import("fmt"
    Userch03 "goproj/IMOOC/ch03/user"//别名,防止同名歧义)funcmain(){
    c := Userch03.User{
        Name:"hi,user",}
    fmt.Println(Userch03.GetCourse(c))}

gin

github链接

package main

import("net/http""github.com/gin-gonic/gin")funcmain(){
  r := gin.Default()
  r.GET("/ping",func(c *gin.Context){
    c.JSON(http.StatusOK, gin.H{"message":"pong",})})
  r.Run()// listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")}

首次使用时,包的导入报错:
鼠标放在"github.com/gin-gonic/gin",出现提示框,点击Sycn…,等一会报错消失
Sync过程自动下载,可以在go.mod中看到

在这里插入图片描述

或者在终端打开、go mod tidy

在这里插入图片描述

单元测试

package main

funcadd(a, b int)int{return a + b
}
package main

import"testing"funcTestAdd(t *testing.T){if testing.Short(){
        t.Skip("short模式")}
    re :=add(1,2)if re !=3{
        t.Errorf("expect:%d,actual:%d",3, re)}}

终端go test
在这里插入图片描述
测试函数前的运行箭头右键后
在这里插入图片描述

在这里插入图片描述

基于表格

funcTestAdd2(t *testing.T){var dataset =[]struct{
        a   int
        b   int
        out int}{{1,1,2},{-9,8,1},{0,0,0},}for_, value :=range dataset {
        re :=add(value.a, value.b)if re != value.out {
            t.Errorf("expect:%d,actual:%d",3, re)}}}

性能测试

const numbers =10000funcBenchmarkStringSprintf(b *testing.B){
    b.ResetTimer()for i :=0; i < b.N; i++{var str stringfor j :=0; j < numbers; j++{
            str = fmt.Sprintf("%s%d", str, j)}}
    b.StopTimer()}funcBenchmarkStringAdd(b *testing.B){
    b.ResetTimer()for i :=0; i < b.N; i++{var str stringfor j :=0; j < numbers; j++{
            str += strconv.Itoa(j)}}
    b.StopTimer()}funcBenchmarkStringBuilder(b *testing.B){
    b.ResetTimer()for i :=0; i < b.N; i++{var builder strings.Builder
        for j :=0; j < numbers; j++{
            builder.WriteString(strconv.Itoa(j))}_= builder.String()}
    b.StopTimer()}

并发编程

package main

import("fmt""time")funcasyncPrint(){
    time.Sleep(time.Second)
    fmt.Println("hi")}funcmain(){goasyncPrint()
    fmt.Println("main")
    time.Sleep(2* time.Second)
    fmt.Println("main2")}
import"fmt"funcmain(){

    fmt.Println("method1")for i :=0; i <100; i++{gofunc(){
            fmt.Println(i)}()}//fmt.Println("method2")//for i := 0; i < 100; i++ {//    tmp := i//    go func() {//        fmt.Println(tmp)//    }()//}//fmt.Println("method3")//for i := 0; i < 100; i++ {//    go func(i int) {//        fmt.Println(i)//    }(i)//}}

waitgroup

package main

import("fmt""sync")funcmain(){var wg sync.WaitGroup
    wg.Add(100)
    fmt.Println("method3")for i :=0; i <100; i++{gofunc(i int){defer wg.Done()
            fmt.Println(i)}(i)}
    wg.Wait()}

互斥锁mutex

package main

import("fmt""sync""sync/atomic")var total int32var wg sync.WaitGroup
var lock sync.Mutex

funcadd(){defer wg.Done()for i :=0; i <10000; i++{
        atomic.AddInt32(&total,1)//lock.Lock()//total += 1//lock.Unlock()}}funcsub(){defer wg.Done()for i :=0; i <10000; i++{
        atomic.AddInt32(&total,-1)//lock.Lock()//total -= 1//lock.Unlock()}}funcmain(){
    wg.Add(2)goadd()gosub()
    wg.Wait()
    fmt.Println(total)
    fmt.Println("all done")}

读写锁rwlock

package main

import("fmt""sync""time")funcmain(){var rwlock sync.RWMutex
    var wg sync.WaitGroup

    wg.Add(6)//写锁gofunc(){
        time.Sleep(3* time.Second)
        rwlock.Lock()defer rwlock.Unlock()
        fmt.Println("writing")
        time.Sleep(5* time.Second)
        fmt.Println("write finish")}()

    time.Sleep(time.Second)//读锁for i :=0; i <5; i++{gofunc(){defer wg.Done()for j :=0; j <10; j++{
                rwlock.RLock()
                time.Sleep(500* time.Millisecond)
                fmt.Println("read")
                rwlock.RUnlock()}}()}
    wg.Wait()}

channel

package main

import"fmt"funcmain(){//有缓存var msg1 chanstring
    msg1 =make(chanstring,1)//1是缓存空间大小
    msg1 <-"harry"
    data :=<-msg1
    fmt.Println(data)//无缓存,happen-before机制var msg2 chanstring
    msg2 =make(chanstring,0)gofunc(msg2 chanstring){
        data2 :=<-msg2
        fmt.Println(data2)}(msg2)
    msg2 <-"potter"var msg3 chanint
    msg3 =make(chanint,2)gofunc(msg3 chanint){for data3 :=range msg3 {
            fmt.Println(data3)}
        fmt.Println("all done")}(msg3)
    msg3 <-1
    msg3 <-2close(msg3)var ch1 chanint//双向var ch2 chan<-int//只写入var ch3 <-chanint//只读取
    
    c :=make(chanint,3)var send chan<-int= c
    var receive <-chanint= c
}

打印数字和字母

package main

import("fmt""time")var number, letter =make(chanbool),make(chanbool)funcprintNum(){
    i :=1for{<-number
        fmt.Printf("%d%d", i, i+1)
        i +=2
        letter <-true}`在这里插入代码片`}funcprintLetter(){
    i :=0
    str :="ABCDEFGHIJKLMNOPQRSTUVWXYZ"for{<-letter
        if i >=len(str){return}
        fmt.Print(str[i : i+2])
        i +=2
        number <-true}}funcmain(){goprintNum()goprintLetter()
    number <-true
    time.Sleep(100* time.Second)}

select

package main

import("fmt""time")// 空结构体不占内存、channel多线程安全var done =make(chanstruct{})funcg1(ch1 chanstruct{}){
    time.Sleep(time.Second)
    ch1 <-struct{}{}}funcg2(ch2 chanstruct{}){
    time.Sleep(1* time.Second)
    ch2 <-struct{}{}}funcmain(){
    ch1 :=make(chanstruct{})
    ch2 :=make(chanstruct{})gog1(ch1)gog2(ch2)//执行先就绪的channel,都就绪则随机(防止饥饿)//select {//case <-ch1://    fmt.Println("g1 done")//case <-ch2://    fmt.Println("g2 done")//default://    fmt.Println("default")//}

    timer := time.NewTimer(5* time.Second)select{case<-ch1:
        fmt.Println("g1 done")case<-ch2:
        fmt.Println("g2 done")case<-timer.C:
        fmt.Println("time our")return}}

context

package main

import("fmt""sync""time")var wgc sync.WaitGroup

funccpuInfo(stop chanstruct{}){defer wgc.Done()for{select{case<-stop:
            fmt.Println("退出CPU监控")returndefault:
            time.Sleep(2* time.Second)
            fmt.Println("CPU信息")}}}funcmain(){var stop =make(chanstruct{})
    wgc.Add(1)gocpuInfo(stop)
    time.Sleep(6* time.Second)
    stop <-struct{}{}
    wgc.Wait()
    fmt.Println("监控完成")}
package main

import("context""fmt""sync""time")var wgc2 sync.WaitGroup

funccpuInfo2(ctx context.Context){defer wgc2.Done()for{select{case<-ctx.Done():
            fmt.Println("退出CPU监控")returndefault:
            time.Sleep(2* time.Second)
            fmt.Println("CPU信息")}}}funcmain(){
    wgc2.Add(1)
    ctx, cancel := context.WithCancel(context.Background())gocpuInfo2(ctx)
    time.Sleep(6* time.Second)cancel()
    wgc2.Wait()
    fmt.Println("监控完成")}

本文转载自: https://blog.csdn.net/weixin_65199878/article/details/131990729
版权归原作者 B.D.S. 所有, 如有侵权,请联系我们删除。

“慕课网Go-4.package、单元测试、并发编程”的评论:

还没有评论