2016-02-24 13 views
5

मुझे उत्सुकता है कि निम्नलिखित क्यों काम नहीं करते हैं। सामान्य तौर पर select एक default: साथ गतिरोध को रोकता है, लेकिन इस मामले में नहीं:चैनल के साथ चयन करें <- <- चैनल

package main 

import "fmt" 

func main() { 
    a := make(chan int) 
    b := make(chan int) 

    select { 
    case a <- <- b: 
     fmt.Println("this is impossible") 
    default: 
     fmt.Println("select worked as naively expected") 
    } 
} 

जाहिर है यह <- <- पसंद नहीं करता है, लेकिन मैं सोच रहा हूँ क्या सतह के पीछे यहां चल रहा है। अन्य परिस्थितियों में <- <- की अनुमति है (हालांकि शायद अनुशंसित नहीं है)।

उत्तर

6

a <- <- ba<- (<-b) के रूप में ही है, क्योंकि वाम-पंथी chan साथ <- ऑपरेटर सहयोगियों संभव है।

तो select में एक प्रेषण ऑपरेशन के साथ case है (a<- (something) के रूप में)। और यहां क्या होता है कि प्रेषण कथन की दाईं ओर की अभिव्यक्ति (मूल्य भेजने के लिए) का मूल्यांकन पहले किया जाता है - जो <-b है। लेकिन इस हमेशा के लिए अवरुद्ध कर देगा (क्योंकि कोई भी b पर कुछ भी भेज रहा है), इसलिए:

fatal error: all goroutines are asleep - deadlock!

प्रासंगिक अनुभाग फार्म Spec: Select statements:

Execution of a "select" statement proceeds in several steps:

  1. For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement. The result is a set of channels to receive from or send to, and the corresponding values to send. Any side effects in that evaluation will occur irrespective of which (if any) communication operation is selected to proceed. Expressions on the left-hand side of a RecvStmt with a short variable declaration or assignment are not yet evaluated.

  2. If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.

  3. ...

तो अगर default मौजूद है, select यदि कोई भी अवरुद्ध होने से रोकने करता है संचार चरण 2 में आगे बढ़ सकते हैं, लेकिन आपका कोड चरण 1 में फंस गया है।


बस पूरा होने के लिए, अगर वहाँ एक goroutine कि b पर एक मूल्य भेजना होगा, तो <- b के मूल्यांकन ब्लॉक नहीं होगा, इसलिए select के निष्पादन के चरण 2 में अटक नहीं होता है, और आप "select worked as naively expected" अपेक्षित (क्योंकि a से प्राप्त अभी भी इसलिए आगे नहीं बढ़ सकता है default चुना जाएगा) देखना होगा:

go func() { b <- 1 }() 

select { 
    // ... 
} 

यह Go Playground पर की कोशिश करो।

संबंधित मुद्दे