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()
}
go 并发编程实践Day1
最新推荐文章于 2021-12-25 18:09:59 发布