您的位置 首页 golang

Golang 并发的退出

Golang 并发的退出

 import (
    "flag"
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
    "sync"
    "time"
)
//一个已经被关闭的channel不会阻塞,已经被关闭的channel会实时返回
//goroutine退出,关闭done来进行广播
var done = make(chan struct{})
//判断done是否关闭,即是否执行goroutine退出
func cancelled() bool {
    select {
    case <-done:
        return true
    default:
        return false
    }
}
//获取目录dir下的文件大小
func walkDir(dir string, wg *sync.WaitGroup, fileSizes chan<- int64) {
    defer wg.Done()
    if cancelled() {
        return
    }
    for _, entry := range dirents(dir) {
        if entry.IsDir() { //目录
            wg.Add(1)
            subDir := filepath.Join(dir, entry.Name())
            go walkDir(subDir, wg, fileSizes)
        } else {
            fileSizes <- entry.Size()
        }
    }
}
//sema is a counting semaphore for limiting concurrency in dirents
var sema = make(chan struct{}, 20)
//读取目录dir下的文件信息
func dirents(dir string) []os.FileInfo {
    select {
    case sema <- struct{}{}: //acquire token
    case <-done:
        return  nil // cancelled
    }
    defer func() { <-sema }() //release token
    entries, err := ioutil.ReadDir(dir)
    if err != nil {
        fmt.Fprintf(os.Stderr, "du: %vn", err)
        return nil
    }
    return entries
}
//输出文件数量的大小
func printDiskUsage(nfiles, nbytes int64) {
    fmt.Printf("%d files %.1f GBn", nfiles, float64(nbytes)/1e9)
}
//提供-v 参数会显示程序进度信息
var verbose = flag.Bool("v", false, "show verbose progress messages")
func Start() {
    flag.Parse()
    roots := flag.Args() //需要统计的目录
    if len(roots) == 0 {
        roots = []string{"."}
    }
    fileSizes := make(chan int64, 5)
    var wg sync.WaitGroup
    for _, root := range roots {
        wg.Add(1)
        go walkDir(root, &wg, fileSizes)
    }
    go func() {
        os.Stdin.Read(make([]byte, 1)) //从标准输入读取一个字符,执行goroutine退出
        close(done)
    }()
    go func() {
        wg.Wait() //等待goroutine结束
        close(fileSizes)
    }()
    var tick <-chan time.Time
    if *verbose {
        tick = time.Tick(100 * time.Millisecond) //输出时间间隔
    }
    var nfiles, nbytes int64
loop:
    for {
        select {
        case <-done:
                //to allow existing goroutines to finish
            for range fileSizes { //fileSizes关闭时,for循环会自动结束
                //Do nothing
            }
            return
        case size, ok := <-fileSizes:
            if !ok {
                break loop
            }
            nfiles++
            nbytes += size
        case <-tick:
            printDiskUsage(nfiles, nbytes)
        }
    }
    printDiskUsage(nfiles, nbytes)
}  

文章来源:智云一二三科技

文章标题:Golang 并发的退出

文章地址:https://www.zhihuclub.com/86943.shtml

关于作者: 智云科技

热门文章

评论已关闭

39条评论

  1. For the many men affected by ED, the condition can be an unfortunate source of embarrassment and frustration The dosage of this medicine is strongly dependent on the sexual activity of a person

  2. Save at over 68,000 pharmacies nationwide, including Evaluation of change in Intra-vaginal Ejaculation Latency Time IELT compared to baseline Time Frame 4 weeks

  3. 40,41 There was a weaker effect seen in the low-dose OAD regimen for patients who did not have a cardiovascular disorder and for patients who smoked

  4. Isotretinoin can cause very serious birth defects, so it s not safe for pregnant women, and doctors monitor patients closely if they prescribe it. All generic drug interactions for bismuth subcit k- metronidazole- tetracycline oral lists will include brand and generic names.

  5. 418 FLUDARABINA 50 mg BLAÚ FARMACÉUTICA 140 mg Caja x 10 cáps my joints ace and i keep getting yeast infections and later I was told this medication has triggered herpes and I cannot understand this when I have not had sex form or fashion in 30yrs

  6. enzalutamide will decrease the level or effect of etravirine by affecting hepatic intestinal enzyme CYP3A4 metabolism

  7. D Limonene and its metabolites, perillic acid, dihydroperillic acid, uroterpenol, and limonene1, 2 diol, may inhibit tumor growth via inhibition of p21 dependent signaling and apoptosis resulting from induction of the transforming growth factor beta signaling pathway 9 10

  8. Telangiectasias become prominent, especially with cumulative photodamage Besides, the follicular response was relatively higher in the calcium- vitamin D group compared to the metformin group, but the differences between the groups were statistically insignificant

  9. Moreover, another study found that the P2X7 receptor is relevant to the release of sEVs in murine macrophages with brief stimulation by ATP 45

  10. J Assist Reprod Genet 10 53 57 The significance of a positive margin R1 or R2 resection is highly debated

  11. stage 1 cancer in the Surveillance, Epidemiology, and End Results SEER Medicare data linkage between December 2002 and December 2007

  12. While clomiphene citrate is generally well tolerated, common side effects have been reported including vasomotor flushes, breast tenderness, pelvic discomfort, and mood swings

  13. They consist of protein bound pigments, including chlorophyll, beta carotene, lutein, and zeaxanthin, and antioxidants, such as carotenoids and vitamin E 9 Functional and morphological evaluation of the meibomian glands in the assessment of meibomian gland dysfunction subtype and severity

  14. Van Nespen, T An ovulation test strip, or ovulation predictor kit, OPK can help you identify the most fertile days during your monthly cycle that is, the day or two leading up to ovulation when sex or insemination is most likely to lead to pregnancy

  15. Ofirok provided a spectacular four story building on the most prosperous Fifth Avenue how does calcium channel blockers work in Lille City and 100, 000 gold coins for the Hammer of War, which was a fulfillment of the previous promise

  16. Dasatinib exerted a dose dependent growth inhibition, and 0 Invasive recurrences were observed in 4

  17. The women, enrolled between 17 June 1999 and 4 August 2015, received ovarian suppression ie, goserelin or triptorelin or ablation along with randomized treatment and were followed up for a median of 8 years However some SI s come in 40mg so you can either take 80- 120mg as a starting dose

  18. avodart valsartan hydrochlorothiazide princeps Prince Charles already holds the records for being the oldest and third longest serving Prince of Wales since it became the title of the heir apparent and also the longest serving heir to the throne in British history

  19. 4 bovine serum albumin Sigma, 100 penicillin streptomycin for two weeks until the mammosphere became visible

  20. Some sources describe an alternative, yet not definitive, minimally invasive therapy for treatment, such as injecting triamcinolone at the dosage of 10 mg mL for the trunk and 3 mg mL for the face

  21. The objective of this retrospective study was to assess the effects of anastrozole and tamoxifen on weight change in postmenopausal women

  22. Samples were subsequently passed over a Qiagen RNeasy column Qiagen, Valencia, CA for control of small fragments that have been shown to affect reverse transcriptase reaction and hybridization quality unpublished data

  23. Minocycline induced autoimmune hepatitis and systemic lupus erythematosus like syndrome Peyton ODdRIrrrvfEXTPAga 6 4 2022

网站地图