Created
July 31, 2024 15:31
-
-
Save ValeryVerkhoturov/8655e2d63276bd792958c3a8b1cfce2a to your computer and use it in GitHub Desktop.
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
// Просмотреть код, назвать, что выведется в stdout | |
package main | |
import ( | |
"fmt" | |
"time" | |
"sync" | |
) | |
type Agent struct { | |
ID int | |
Enabled bool | |
} | |
func (a *Agent) Enable() { | |
a.Enabled = true | |
} | |
type Enabler interface { | |
Enable() | |
} | |
// 1. Инициализация слайса агентов | |
// 2. Дополнение слайса сторонними агентами | |
// 3. Потоковая обработка объектов - отправка на выполнение работы | |
// 4. Потоковая обработка объектов - активация, сохранение в БД и распечатка результатов | |
func main() { | |
agents := make([]Agent, 0, 5) | |
for i := 0; i < 2; i++ { | |
agents = append(agents, Agent{ID: i}) | |
} | |
addThirdPartyAgents(&agents) | |
pipe := make(chan Enabler) | |
wg := sync.WaitGroup{} | |
wg.Add(len(agents)) | |
go pipeEnableAndSend(pipe, agents) | |
go pipeProcess(pipe, &wg) | |
wg.Wait() | |
} | |
// {0 true} | |
// {1 true} | |
// {4 true} | |
// {5 true} | |
func addThirdPartyAgents(agents *[]Agent) { | |
thirdParty := []Agent{ | |
{ID: 4}, | |
{ID: 5}, | |
} | |
*agents = append(*agents, thirdParty...) | |
} | |
func pipeEnableAndSend(pipe chan Enabler, agents []Agent) { | |
for _, a := range agents { | |
a.Enable() | |
pipe <- &a | |
} | |
} | |
func pipeProcess(pipe chan Enabler, wg *sync.WaitGroup) { | |
var a Enabler | |
for { | |
select { | |
case a = <-pipe: | |
dbWrite(a) | |
wg.Done() | |
} | |
} | |
} | |
var dbWrite = func(a interface{}) { | |
fmt.Println(a) | |
time.Sleep(time.Second * 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment