zoukankan      html  css  js  c++  java
  • go 面试题

    有四个线程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
    }
  • 相关阅读:
    echarts之tooltip
    js随笔
    在wex5平台grid显示问题
    JSON.parse()和JSON.stringify()区别
    在wex5平台grid里面的gridselect下拉不能显示汉字问题
    wex5平台放入tabs组件后运行时显示空白
    正整数求n不用sqrt
    leetcode1143最长公共子序列
    美团Java一面(2020.3.19)
    leetcode138. 复制带随机指针的链表
  • 原文地址:https://www.cnblogs.com/LoveHe/p/9001813.html
Copyright © 2011-2022 走看看