第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我如何使這個程序線程安全,通道是否是最好的實現(xiàn),如果是,如何實現(xiàn)?

我如何使這個程序線程安全,通道是否是最好的實現(xiàn),如果是,如何實現(xiàn)?

Go
SMILET 2022-11-23 19:17:30
我正在使用 Golang,我試圖讓這個程序線程安全。它以一個數(shù)字作為參數(shù)(即要啟動的消費者任務(wù)的數(shù)量),從輸入中讀取行,并累積字數(shù)。我希望線程是安全的(但我不希望它只是鎖定所有內(nèi)容,它需要高效)我應(yīng)該使用通道嗎?我該怎么做呢?package mainimport (    "bufio"    "fmt"    "log"    "os"    "sync")// Consumer task to operate on queuefunc consumer_task(task_num int) {        fmt.Printf("I'm consumer task #%v ", task_num)    fmt.Println("Line being popped off queue: " + queue[0])    queue = queue[1:]}// Initialize queuevar queue = make([]string, 0)func main() {    // Initialize wait group     var wg sync.WaitGroup    // Get number of tasks to run from user    var numof_tasks int    fmt.Print("Enter number of tasks to run: ")    fmt.Scan(&numof_tasks)        // Open file    file, err := os.Open("test.txt")    if err != nil {        log.Fatal(err)    }    defer file.Close()    // Scanner to scan the file    scanner := bufio.NewScanner(file)    if err := scanner.Err(); err != nil {        log.Fatal(err)    }    // Loop through each line in the file and append it to the queue    for scanner.Scan() {        line := scanner.Text()          queue = append(queue, line)    }    // Start specified # of consumer tasks    for i := 1; i <= numof_tasks; i++ {        wg.Add(1)        go func(i int) {             consumer_task(i)             wg.Done()        }(i)    }    wg.Wait()    fmt.Println("All done")    fmt.Println(queue)}
查看完整描述

1 回答

?
繁花如伊

TA貢獻2012條經(jīng)驗 獲得超12個贊

您在切片上存在數(shù)據(jù)競爭queue。并發(fā) goroutines,當通過sync.Mutex鎖以受控方式從隊列頭部彈出元素時?;蛘呤褂靡粋€通道來管理工作項的“隊列”。


要將您所擁有的轉(zhuǎn)換為使用通道,請更新工作人員以將輸入通道作為您的隊列 - 并在通道上進行范圍,以便每個工作人員可以處理多個任務(wù):


func consumer_task(task_num int, ch <-chan string) {


    fmt.Printf("I'm consumer task #%v\n", task_num)

    for item := range ch {

        fmt.Printf("task %d consuming: Line item: %v\n", task_num, item)

    }

    // each worker will drop out of their loop when channel is closed

}

從切片更改queue為頻道和 feed 項目,如下所示:


queue := make(chan string)


go func() {

    // Loop through each line in the file and append it to the queue

    for scanner.Scan() {

        queue <- scanner.Text()

    }

    close(queue) // signal to workers that there is no more items

}()

然后只需更新您的工作調(diào)度程序代碼以添加頻道輸入:


go func(i int) {

    consumer_task(i, queue) // add the queue parameter

    wg.Done()

}(i)

https://go.dev/play/p/AzHyztipUZI


查看完整回答
反對 回復(fù) 2022-11-23
  • 1 回答
  • 0 關(guān)注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號