首页 > 其他分享 >Go - semaphore

Go - semaphore

时间:2024-06-13 20:46:07浏览次数:21  
标签:err fmt results Println semaphore Go os

 

 

 

 

 

 

 

 

 

package main

import (
    "context"
    "fmt"
    "os"
    "strconv"
    "time"

    "golang.org/x/sync/semaphore"
)

func worker(n int) int {
    square := n * n
    time.Sleep(time.Second)
    return square
}

func main() {
    if len(os.Args) != 2 {
        fmt.Println("Need #jobs!")
        os.Exit(1)
    }

    var workers = 4
    var sem = semaphore.NewWeighted(int64(workers))

    nJobs, err := strconv.Atoi(os.Args[1])
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    // Where to store the results
    var results = make([]int, nJobs)
    // Needed by Acquire()
    ctx := context.TODO()
    for i := range results {
        err = sem.Acquire(ctx, 1)
        if err != nil {
            fmt.Println("Cannot acquire semaphore:", err)
            break
        }

        go func(i int) {
            defer sem.Release(1)
            temp := worker(i)
            results[i] = temp
        }(i)
    }

    err = sem.Acquire(ctx, int64(workers))
    if err != nil {
        fmt.Println(err)
    }

    for i, v := range results {
        fmt.Println(i, "->", v)
    }
}

 

zzh@ZZHPC:/zdata/Github/ztest$ go run main.go 5
0 -> 0
1 -> 1
2 -> 4
3 -> 9
4 -> 16

 

标签:err,fmt,results,Println,semaphore,Go,os
From: https://www.cnblogs.com/zhangzhihui/p/18246707

相关文章

  • golang reflect 反射机制的使用场景
     Go语言中的reflect包提供了运行时反射机制,允许程序在运行时检查和操作任意对象的数据类型和值。 以下是reflect包的一些典型使用场景: 1.动态类型判断与转换:当需要处理多种类型的变量且具体类型直到运行时才能确定时,可以使用反射来检查变量的实际类型,并在可能的情况......
  • Dragon Boat Festival
    TheDragonBoatFestivalisaspecialholidayinChina.Ithappensonthefifthdayofthefifthmonthinthelunarcalendar.It'satimetorememberanoldpoetnamedQuYuanwholovedhiscountryverymuch.Today,wecelebratetheDragonBoatFesti......
  • FastAPI-7:框架比较(Flask、Django及FastAPI)
    7框架比较(Flask、Django及FastAPI)关于一个新的Web框架,您可能想知道的第一件事就是如何入门,而一种自上而下的方法就是定义路由(从URL和HTTP方法到函数的映射)。7.1FlaskFlask自称是微框架。它提供基本功能,你可以根据需要下载第三方软件包进行补充。它比Django小,入门时学习......
  • 在Django中使用Celery
    首先需要确保安装依赖pipinstallceleryrediseventlet在创建的app文件内添加tasks.py#app01/tasks.pyfromceleryimportshared_task@shared_taskdefsimple_task():print('Taskexecutedsuccessfully')在项目目录下(与settings.py文件同级)添加celery.py......
  • Dragon Boat Festival
    DragonBoatFestivalTheDragonBoatFestival,alsocalledtheDuanwuFestival,iscelebratedonthefifthdayofthefifthmonthaccordingtotheChinesecalendar.Forthousandsofyears,thefestivalhasbeenmarkedbyeatingzongziandracingdragon......
  • Dragon Boat Festival
    TheDragonBoatFestival,atime-honoredtraditioninChina,encapsulatestheessenceofculture,family,andperseverance.ThisdayisalwaysfilledwithmarvelousdelightforaslongasIcanremember.Lastyear'sDragonBoatFestivalseemedlikey......
  • gorm
    模型定义|GORM-ThefantasticORMlibraryforGolang,aimstobedeveloperfriendly.模型定义GORM通过将Go结构体(Gostructs)映射到数据库表来简化数据库交互。了解如何在GORM中定义模型,是充分利用GORM全部功能的基础。模型是使用普通结构体定义的。这些结构体可以......
  • The Enchantment of the Dragon Boat Festival
    TheEnchantmentoftheDragonBoatFestivalAstheearlyJuneiscoming,theringoftheDragonBoatFestivalhadunconsciouslyknocked.IwastransportedbacktotheenchantingatmosphereoftheDragonBoatFestival.Thisfestival,deeplyrootedinChin......
  • The Dragon Boat Festival
    TheDragonBoatFestivalapproaching,abuzzofanticipationfillstheair.Thisancientcelebration,passeddownfromgenerationtogeneration,notonlyrepresentsatimeforcommunity,butalsoajourneyofremembrance.Actually,Ididn'tpayattent......
  • Drangon Boat Festival
    DragonBoatFestival,alsoknownas DuanwuFestival,isatraditionalCbinesefestivalcelebratedonthefifthdayofthefifthmonthinthelunarcalendar.Thisyear,itfallsonJune14thintheGregoriancalendar.ThefestivaliswidelycelebratedinC......