There are four threads 1, 2, 3, 4. The function of thread 1 is to output 1, the function of thread 2 is to output 2, and so on... Now there are four files ABCD. Initially empty. Now let's make the four files look like this:
A:1 2 3 4 1 2....
B:2 3 4 1 2 3....
C:3 4 1 2 3 4....
D:4 1 2 3 4 1....
In the interview last Friday, the interview gave a go thread question. At that time, I thought of a very stupid way to achieve it. Now I will attach the code after optimization. If there is a better Daniel, you can reply later! ! !
package main import ( "log" "os" ) func main() { a, _ := os.OpenFile("./a.txt", os.O_WRONLY|os.O_APPEND, 0666) b, _ := os.OpenFile("./b.txt", os.O_WRONLY|os.O_APPEND, 0666) c, _ := os.OpenFile("./c.txt", os.O_WRONLY|os.O_APPEND, 0666) d, _ := os.OpenFile("./d.txt", os.O_WRONLY|os.O_APPEND, 0666) files := []*os.File{a, b, c, d} i := 0 sign := make(chan int, 1) for i < 100 { i++ sign <- 1 go out1(files[0], sign) sign <- 1 go out2(files[1], sign) sign <- 1 go out3(files[2], sign) sign <- 1 go out4(files[3], sign) files = append(files[len(files)-1:], files[:len(files)-1]...) } a.Close() b.Close() c.Close() d.Close() } func out2(f *os.File, c chan int) int { f.Write([]byte("2 ")) // f.Close() log.Println(f.Name() + " write finish...") <-c return 2 } func out3(f *os.File, c chan int) int { f.Write([]byte("3 ")) // f.Close() log.Println(f.Name() + " write finish...") <-c return 3 } func out4(f *os.File, c chan int) int { f.Write([]byte("4 ")) // f.Close() log.Println(f.Name() + " write finish...") <-c return 4 }