1114. Print in Order 按序列印

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

本题要求阻塞一众并发的 Goroutine,然后按 One Two Three 的逻辑顺序列印结果

package goroutine

import "fmt"

var chFir = make(chan int)
var chSec = make(chan int)
var chThi = make(chan int)

func printFir() {
    fmt.Print("first")
    chFir <- 1
}

func printSec() {
    <-chFir
    fmt.Print("second")
    chSec <- 2
}

func printThi() {
    <-chSec
    fmt.Print("third")
    chThi <- 3
}

func PrintABC(arr []int) {  
    // arr := []int{1,2,3}
    funcList := map[int]func(){1: printFir, 2: printSec, 3: printThi}
    for _, v := range arr {
        go funcList[v]()
    }
    <-chThi
}

作者:li-er-dan-w
链接:https://leetcode-cn.com/problems/print-in-order/solution/golangxie-cheng-shi-xian-by-li-er-dan-w-kczv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
PrintABC

相关文章:

  • 2021-11-28
  • 2021-11-13
  • 2021-11-27
  • 2021-11-02
  • 2022-01-21
  • 2021-11-10
  • 2022-12-23
猜你喜欢
  • 2021-06-20
  • 2020-07-24
  • 2021-09-16
  • 2022-12-23
  • 2021-05-24
  • 2022-12-23
  • 2019-06-19
相关资源
相似解决方案