惜风不起、唯有努力!
golang协程和互斥锁,管道简单使用

golang协程和互斥锁,管道简单使用

package main

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

var (
	//声明并初始化一个空map
	numMap = make(map[int]int, 10)
	//一个全局的互斥锁
	lock sync.Mutex
)

//计算函数,把结果放入map中
func counts(numX int)  {
	rel := 1
	for i:=1; i<=numX; i++{
		rel *= i
		fmt.Println(rel)
	}
	//写互斥锁,防止map被并发读而异常
	lock.Lock()
	//add map
	numMap[numX] = rel
	lock.Unlock()
}

func main()  {
	//计算1-15的阶乘
	for i:=1;i<=15;i++{
		go counts(i)
	}
        //睡眠以防主函数提前退出
	time.Sleep(time.Second * 5)
	//读互斥锁
	lock.Lock()
	for k,v := range numMap{
		fmt.Printf("map(%d)=%d\n",k,v)
	}
	lock.Unlock()
}

协程和管道使用

package main

import (
	"fmt"
	"time"
)

var (
	numChan  = make(chan int, 30)
	exitChan = make(chan bool, 1)
)

func WData() {
	for i := 1; i <= 30; i++ {
		fmt.Println("w ---> ",i)
		time.Sleep(time.Second * 1)
		numChan <- i
	}
	//如果不关闭,下面函数就会死锁了
	close(numChan)
}

func RData() {
	for {
		v, ok := <-numChan
		if !ok {
			break
		}
		fmt.Printf("func read---> %d\n", v)
	}
	//向退出管道发送信号
	exitChan <- true
	close(exitChan)
}

func main() {
	go WData()
	go RData()

	//循环监听exit管道信号
	for {
		_, ok := <-exitChan
		if !ok {
			break
		}
	}
	fmt.Println("main func exit......")

}

发表回复

您的电子邮箱地址不会被公开。