Last active
July 5, 2023 06:58
-
-
Save shravanasati/e4b5b72ec959ff32c2e1077d180d2185 to your computer and use it in GitHub Desktop.
simple go program to illustrate a central goroutine accepting requests and sending back responses to multiple waiting goroutines
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 main | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
"github.com/google/uuid" | |
) | |
type request struct { | |
id uuid.UUID | |
delay int | |
} | |
type response struct { | |
id uuid.UUID | |
value string | |
} | |
type central struct { | |
listener chan request | |
speakers map[uuid.UUID]*chan response | |
sync.Mutex | |
} | |
func newCentral() *central { | |
return ¢ral{ | |
listener: make(chan request), | |
speakers: make(map[uuid.UUID]*chan response), | |
} | |
} | |
func (c *central) processor() { | |
for r := range c.listener { | |
fmt.Println("request recieved") | |
time.Sleep(time.Second * time.Duration(r.delay)) | |
c.Lock() | |
requiredCh := *(c.speakers[r.id]) | |
requiredCh <- response{ | |
id: r.id, | |
value: fmt.Sprintf("I slept for %d seconds to stimulate an user interacting.", r.delay), | |
} | |
close(requiredCh) | |
c.Unlock() | |
} | |
fmt.Println("processor finished working") | |
} | |
func (c *central) worker() { | |
genId := uuid.New() | |
c.listener <- request{ | |
id: genId, | |
delay: 1, | |
} | |
respCh := make(chan response) | |
c.Lock() | |
c.speakers[genId] = &respCh | |
c.Unlock() | |
fmt.Println("request sent") | |
resp := <- respCh | |
c.Lock() | |
delete(c.speakers, genId) | |
c.Unlock() | |
fmt.Println("response recieved", resp) | |
} | |
func main() { | |
c := newCentral() | |
var wg sync.WaitGroup | |
for i := 0; i < 5; i++ { | |
wg.Add(1) | |
go func () { | |
c.worker() | |
wg.Done() | |
}() | |
} | |
go func () { | |
c.processor() | |
}() | |
wg.Wait() | |
close(c.listener) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment