Skip to content

Instantly share code, notes, and snippets.

@ionling
Created September 23, 2021 01:52
Show Gist options
  • Save ionling/3899f0a1708d2a61ea5b7ec7980bd44d to your computer and use it in GitHub Desktop.
Save ionling/3899f0a1708d2a61ea5b7ec7980bd44d to your computer and use it in GitHub Desktop.
Implementing golang channel
package channel
import (
"sync"
"time"
)
type Channel struct {
lock sync.Mutex
value interface{}
}
func (c *Channel) Read() (res interface{}) {
for {
c.lock.Lock()
if c.value != nil {
res = c.value
c.value = nil
c.lock.Unlock()
return
}
c.lock.Unlock()
time.Sleep(time.Nanosecond)
}
}
func (c *Channel) Write(x interface{}) {
for {
c.lock.Lock()
if c.value == nil {
c.value = x
c.lock.Unlock()
return
}
c.lock.Unlock()
time.Sleep(time.Nanosecond)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment