两个协程交替打印1到20

本文阅读 1 分钟
首页 golang 正文

题目来源:字节跳动

频次:2

答案:小小

  1. 使用channel
package main

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


func main() {
    wg := &sync.WaitGroup{}
    ch1 := make(chan int)
    ch2 := make(chan int)

    wg.Add(2)
    go say(wg, ch2, ch1)
    go say1(wg, ch1, ch2)
    wg.Wait()
    time.Sleep(1 * time.Second)
}

func say(wg *sync.WaitGroup, ch2 chan int, ch1 chan int) {
    defer wg.Done()
    for i := 1; i <= 10; i++ {
        ch2 <- 2*i - 1
        fmt.Println(<-ch1)
    }
}

func say1(wg *sync.WaitGroup, ch1 chan int, ch2 chan int) {
    defer wg.Done()
    for i := 1; i <= 10; i++ {
        fmt.Println(<-ch2)
        ch1 <- 2 * i
    }
}

2.使用锁

//使用锁
// 一个协程对该变量进行操作时进行加锁,另一个协程等待。
// 释放锁后再进行操作,每次操作进行加1即可

package main
import (
    "fmt"
    "sync"
    "time"
)
type Alternate struct {
    count int
    mu sync.Mutex
}
func main(){
    tong:=Alternate{count: 0}
    go tong.printOld()
    time.Sleep(time.Millisecond*20)
    go tong.printEvent()
    time.Sleep(time.Second*3)
}

// 两个协程,一个获取锁一个等待不断交换
// 打印第一个数
func (tong *Alternate)printOld(){
    for tong.count<20{
        tong.mu.Lock()
        tong.count += 1
        fmt.Println(tong.count)
        tong.mu.Unlock()
    }
    return

}
// 第二个数 = 第一个数 + 1
func (tong *Alternate)printEvent(){
    for tong.count<20{
        tong.mu.Lock()
        tong.count += 1
        fmt.Println(tong.count)
        tong.mu.Unlock()
    }
    return
}
本文来自投稿,不代表本站立场,如若转载,请注明出处:
syncpool的实现原理
« 上一篇 09-17
问了sync.Map(我说我对sync.Pool比较熟,就说Pool了)
下一篇 » 09-17

发表评论

发表评论