使用两个go协程顺序打印一个字符串
研大石
2022年05月14日 22:28

  

记录一次面试遇到的编程题,进大厂必备题型。 

代码块
Go
自动换行
复制代码
package main

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

func main() {
	var wg sync.WaitGroup
	wg.Add(2)
	str := "hello,world!"
	str1 := []byte(str)
	sc := make(chan byte, len(str))
	count := make(chan int)
	for _, v := range str1 {
		sc <- v
	}
	close(sc)

	go func() {
		defer wg.Done()
		for {
			ball, ok := <-count
			if ok {
				pri, ok1 := <-sc
				if ok1 {
					fmt.Printf("go 2 : %c\n", pri)
				} else {
					close(count)
					return
				}
				count <- ball
			} else {
				return
			}
		}
	}()

	go func() {
		defer wg.Done()
		for {
			time.Sleep(8 * time.Millisecond)
			ball, ok := <-count
			if ok {
				pri, ok1 := <-sc
				if ok1 {
					fmt.Printf("go 1 : %c\n", pri)
				} else {
					close(count)
					return
				}
			} else {
				return
			}
			count <- ball
		}
	}()

	count <- 23
	wg.Wait()
}
复制成功