有四個線程1、2、3、4。線程1的功能就是輸出1,線程2的功能就是輸出2,以此類推.........現在有四個文件ABCD。初始都為空。現要讓四個文件呈如下格式:
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....
上周五面試,面試給了一道go線程的題,當時時間想了一個很笨的方式來實現的,現在優化后附上代碼,如果有更好的大牛可以在后面回復!!!
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 }
