Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

Channels

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Channel သည် goroutine တွေအချင်းချင်း data ပို့/လက်ခံဖို့သုံးတဲ့ typed pipe ပါ။ Data sharing ကို memory ကိုတူတူကိုင်ပြီးပြောင်းတာထက် message ပို့သလိုစီမံချင်တဲ့အခါ channel ကအလွန်အသုံးဝင်ပါတယ်။

go
package main

import "fmt"

func main() {
    messages := make(chan string)

    go func() {
        messages <- "ping"
    }()

    msg := <-messages
    fmt.Println(msg)
}

messages <- "ping" က channel ထဲ message ပို့တာပါ။ msg := <-messages က channel ထဲက message ကိုလက်ခံတာပါ။

You should see
ping

Info

Unbuffered channel မှာ send နဲ့ receive တစ်ဖက်ဖက်မရှိသေးရင် wait လုပ်ပါတယ်။ ဒီ behavior က synchronization အတွက်အသုံးဝင်ပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • ဘယ်သူမှ receive မလုပ်တဲ့ channel ထဲ send လုပ်ရင် deadlock ဖြစ်နိုင်ပါတယ်။ Goroutine flow ကိုစဉ်းစားပြီး channel ကိုပိတ်သင့်တဲ့နေရာမှာ close(channel) သုံးပါ။
Channels | Thuta Learning