Created
September 23, 2021 01:52
-
-
Save ionling/3899f0a1708d2a61ea5b7ec7980bd44d to your computer and use it in GitHub Desktop.
Implementing golang channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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