搜尋
首頁後端開發Golang為什麼通道不採用最後聲明的值?

為什麼通道不採用最後聲明的值?

在PHP中,通道(channel)是一種用於並發程式設計的重要概念。它允許不同的協程(goroutine)之間進行通訊和同步操作。然而,有一個常見的疑問是:「為什麼通道不採用最後聲明的值?」這個問題涉及通道的設計原則和使用方式。通道在接收操作時,會阻塞等待發送方發送資料。當發送方發送完資料後,接收方才能繼續執行。因此,通道的值是在發送方發送資料時確定的,而不是在接收方接收資料時確定的。這是為了確保通訊的可靠性和一致性。所以,即使最後聲明的值在接收方接收時已經改變,通道仍然會採用發送時的值。這樣做可以避免數據的不一致性和混亂,確保溝通的可靠性和準確性。

問題內容

我正在嘗試了解頻道。在這段程式碼中,我聲明了從 1 到 10 的值。最終聲明的值為 10,但是當我列印它時,它總是會傳回 before(8) 之前兩個宣告的值。如果有人能解釋一下,我會很高興。

func main() {
    channel := make(chan int, 3)
    isOver := make(chan bool)

    go func() {
        for val := range channel {
            fmt.Println(val)
        }
        isOver <- true
    }()

    channel <- 1
    channel <- 2
    channel <- 3
    channel <- 4
    channel <- 5
    channel <- 6
    channel <- 7
    channel <- 8
    channel <- 9
    channel <- 10
    close(channel)

    fmt.Println("Channel Value is: ", <-channel)

    <-isOver

}

當我將聲明更改為 8 時,它會傳回之前兩個聲明的值,即 6。

解決方法

因為你為通道設定了3個緩衝區大小!

注意:您的範例在不同的作業系統中具有不同的輸出(例如我得到 Channel 值為:0

設定時間。在程式碼中休眠看看會發生什麼事。在您的程式碼中:

<code>func main() {
    channel := make(chan int)
    isOver := make(chan bool)

    go func() {
        for val := range channel {
            fmt.Println(val)
            // sleep 1 second
            time.Sleep(1 * time.Second)
        }
        isOver <- true
    }()

    channel <- 1
    channel <- 2
    channel <- 3
    channel <- 4
    channel <- 5
    channel <- 6
    channel <- 7
    channel <- 8
    channel <- 9
    channel <- 10
    close(channel)

    fmt.Println("Channel Value is: ", <-channel)
    <-isOver
}

</code>

輸出為:

1
2
3
4
5
6
7
Channel Value is:  8
9
10

注意:了解程式碼中發生的情況的更好方法是逐步追蹤程式碼。

發生了什麼事? 看到這個痕跡:

1 // print 1 and sleep 1s
2,3,4 // stop for get values

3,4 // print 2 and sleep 1
3,4,5 // stop for get value

4,5 // print 3 and sleep 1
4,5,6 // stop for get value

5,6 // print 4 and sleep 1
5,6,7 // stop for get value

6,7 // print 5 and sleep 1
6,7,8 // stop for get value

7,8 // print 6 and sleep 1
7,8,9 // stop for get value

8,9 // print 7 and sleep 1
8,9,10 // stop for get value
// close channel
// in this line get value : fmt.Println("Channel Value is: ", <-channel)

9,10 // before get value
10 // get 9 and sleep 1
// get 10 and sleep 1

// isdone send signal true

在追蹤程式碼中,當通道取得樹值 8,9,10 時,通道關閉,在步驟 2 中發生了事情:

1 - 如果 goroutine 快速取得所有值(通道值為:0)
2 - 如果 goroutine 繁忙(通道值為:7 或 8 或 9 或 10)

有關詳細信息,請參閱此問題:何時使用緩衝通道 並查看此網站以更好地理解:連結

以上是為什麼通道不採用最後聲明的值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
與GO接口鍵入斷言和類型開關與GO接口鍵入斷言和類型開關May 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

使用errors.is和錯誤。使用errors.is和錯誤。May 02, 2025 am 12:11 AM

Go語言的錯誤處理通過errors.Is和errors.As函數變得更加靈活和可讀。 1.errors.Is用於檢查錯誤是否與指定錯誤相同,適用於錯誤鏈的處理。 2.errors.As不僅能檢查錯誤類型,還能將錯誤轉換為具體類型,方便提取錯誤信息。使用這些函數可以簡化錯誤處理邏輯,但需注意錯誤鏈的正確傳遞和避免過度依賴以防代碼複雜化。

在GO中進行性能調整:優化您的應用程序在GO中進行性能調整:優化您的應用程序May 02, 2025 am 12:06 AM

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

GO的未來:趨勢和發展GO的未來:趨勢和發展May 02, 2025 am 12:01 AM

go'sfutureisbrightwithtrendslikeMprikeMprikeTooling,仿製藥,雲 - 納蒂維德象,performanceEnhancements,andwebassemblyIntegration,butchallengeSinclainSinClainSinClainSiNgeNingsImpliCityInsImplicityAndimimprovingingRornhandRornrorlling。

了解Goroutines:深入研究GO的並發了解Goroutines:深入研究GO的並發May 01, 2025 am 12:18 AM

goroutinesarefunctionsormethodsthatruncurranceingo,啟用效率和燈威量。 1)shememanagedbodo'sruntimemultimusingmultiplexing,允許千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

了解GO中的初始功能:目的和用法了解GO中的初始功能:目的和用法May 01, 2025 am 12:16 AM

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

了解GO界面:綜合指南了解GO界面:綜合指南May 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

從恐慌中恢復:何時以及如何使用recover()從恐慌中恢復:何時以及如何使用recover()May 01, 2025 am 12:04 AM

在Go中使用recover()函數可以從panic中恢復。具體方法是:1)在defer函數中使用recover()捕獲panic,避免程序崩潰;2)記錄詳細的錯誤信息以便調試;3)根據具體情況決定是否恢復程序執行;4)謹慎使用,以免影響性能。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中