Last active
August 7, 2023 22:02
-
-
Save rosconap/9dc58bebf402ac32be05c52df8e460e3 to your computer and use it in GitHub Desktop.
Proccess mapper tool
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
// So this code is processing a channel of stuff with uniq id's. Pretend we have incomming stuffpackets | |
// from a network connection that are unsorted and need to be processed per id. The stuff processor will | |
// put these packets in their own channel to be processed with their own routine in thehandlymystuff | |
// function. It looks up the corresponding channel in a map. If the channel does not exists, it will be | |
// created and directly used for the first itteration and so on. | |
// StuffProcessor ... | |
type StuffProcessor struct { | |
StuffChan chan Stuff // ingest unsorted stuff packets from channel. | |
StuffDispatch map[string]chan Stuff // each stuff stream mapped id channel. | |
QuitChan chan bool | |
} | |
// Start StuffProcessor ... | |
func (p *StuffProcessor) Start() { | |
defer func() { | |
p.close() | |
}() | |
for { | |
select { | |
case <-p.QuitChan: | |
break | |
case stuffPacket := <-p.StuffChan: | |
if ch, ok := p.StuffDispatch[stuffpacket.ID]; ok { // channel already created | |
ch <- stuffPacket | |
continue | |
} | |
p.addStuffProcessor(stuffpacket.ID) | |
p.StuffDispatch[key] <- stuffPacket | |
} | |
} | |
} | |
// addStuffProcessor maps a channel with id and fires off a routine to handle it. | |
func (p *StuffProcessor) addStuffProcessor(id string) { | |
p.StuffDispatch[id] = make(chan Stuff) | |
go p.handlemystuff(p.StuffDispatch[id]) | |
} | |
// Close closes all open channels in StuffProcessor | |
func (p *StuffProcessor) close() { | |
close(p.StuffChan) // Close incoming channel first | |
for _, ch := range p.StuffDispatch { // Close per stuff.id channels next | |
close(ch) | |
} | |
} | |
// handlemystuff handles the channel based on the stuff.id you created | |
func func (p *StuffProcessor) handlemystuff(stuff chan Stuff) | |
for { | |
select { | |
case s := <-stuff: | |
// Do what you need to do here | |
fmt.Printf("Processing your %v", stuff.id) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment