go 并发编程实践Day1

func MainDay1() {
	sayHello3()
	calGoroutineNum()
}

func learnMd5(){
	data := []byte("hello world12312312fdsafadsfadfsdhpfauhsfuaohsfuhdsaufsdofhasdfhoasjdfholssfadsfasdfsadfs34324234234232342323423423423423423423423423a")
	has := md5.Sum(data)
	fmt.Println(has)
	fmt.Println(fmt.Sprintf("%x", has))
}

func calGoroutineNum() {
	memConsume := func() uint64 {
		runtime.GC()
		var s runtime.MemStats
		runtime.ReadMemStats(&s)
		return s.Sys
	}
	var c <-chan interface{}
	var wg sync.WaitGroup
	noop := func() {
		wg.Done()
		<-c
	}
	const goroutineNum = 10000
	wg.Add(goroutineNum)
	before := memConsume()
	fmt.Println("before=", before)
	for i := goroutineNum; i > 0; i-- {
		go noop()
	}
	wg.Wait()
	after := memConsume()
	fmt.Println("after=", after)
	fmt.Printf("%.3fkb", float64(after-before)/goroutineNum/1000)
}

func mySqrt1(x int) int {
	if x == 0 {
		return x
	}
	ans := int(math.Exp(0.5 * math.Log(float64(x))))
	if (ans+1)*(ans+1) <= x {
		return ans + 1
	}
	return ans
}

func sayHello(wg sync.WaitGroup) {
	wg.Done()
	fmt.Println("hello")
}

/**
world
*/
func sayHello2() {
	word := "hello"
	var wg sync.WaitGroup
	sayHello := func() {
		defer wg.Done()
		word = "world"
	}
	wg.Add(1)
	go sayHello()
	wg.Wait()
	fmt.Println(word)
}

/**
apple
apple
apple
apple
*/
func sayHello3() {
	var wg sync.WaitGroup
	words := []string{"hello", "lucky", "good", "apple"}
	for _, word := range words {
		wg.Add(1)
		go func() {
			defer wg.Done()
			fmt.Println(word)
		}()
	}
	wg.Wait()
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值