有四个线程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 (
"sync"
"os"
"fmt"
)
var wg sync.WaitGroup
func main() {
wg.Add(4)
f1, _ := os.Create("/tmp/1") //创建文件
f2, _ := os.Create("/tmp/2")
f3, _ := os.Create("/tmp/3")
f4, _ := os.Create("/tmp/4")
ch1 := make(chan int)
ch2 := make(chan int)
ch3 := make(chan int)
ch4 := make(chan int)
go myfun1(ch1,f1)
go myfun1(ch2,f2)
go myfun1(ch3,f3)
go myfun1(ch4,f4)
ch1 <-0
ch2 <-1
ch3 <-2
ch4 <-3
wg.Wait()
f1.Close()
f2.Close()
f3.Close()
f4.Close()
}
func myfun1(ch chan int,f *os.File) {
num := <- ch
//从1开始
t := (num % 4) + 1
f.Write([]byte(fmt.Sprint(t)))
num += 1
//只增长到20
if num == 20 {
wg.Done()
close(ch)
return
}
go myfun1(ch,f)
ch <- num
}