Created
October 31, 2017 04:51
-
-
Save 0qdk4o/3913a549e55b6cc0e3503d7151f6fd73 to your computer and use it in GitHub Desktop.
just a test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 有四个线程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.... | |
// 没必要用chan chan的切换代价是很大的 我一般能不用就不用,观察规律好像这样也可以生成目标文件 | |
// 并且是用四个coroutine 写文件可以先写缓冲区再一次写4K或16K 这样会更高效 但这并不是本问题重点 | |
package main | |
import ( | |
"os" | |
"time" | |
) | |
var ( | |
data = [4]string{"1", "2", "3", "4"} | |
filenames = [4]string{"A", "B", "C", "D"} | |
files [4]*os.File | |
) | |
func openFiles() { | |
for i, name := range filenames { | |
f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) | |
if err != nil { | |
panic("open file failed.") | |
} | |
files[i] = f | |
} | |
} | |
func closeFiles() { | |
for _, v := range files { | |
v.Close() | |
} | |
} | |
func thread(f *os.File, p int) { | |
for { | |
f.WriteString(data[p%4]) | |
p++ | |
} | |
} | |
func main() { | |
openFiles() | |
defer closeFiles() | |
p := 0 | |
for i := range files { | |
go thread(files[i], p+i) | |
} | |
select { | |
case <-time.Tick(time.Microsecond * 1): | |
os.Exit(0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment