Answer the question
In order to leave comments, you need to log in
How to implement multithreading in go?
Let's say there are several telephone exchanges from which it is necessary to simultaneously collect information and write it to some database.
Tell me how best to implement this action, tk. now the only thing that comes to mind:
in an endless loop we pass through all the stations. With the help of channels, we wait until we receive a response from all stations, and move on.
And I would like that if the first and third stations respond quickly - do not wait for the answer of the second and make a request to the first and third again, etc.
An example code, for clarity, as it is presented now:
func someRequest(phone string, ch chan bool) {
fmt.Println(phone)
//time.Sleep(time.Second * 5) //Долгая операция. Для разных phone - разная по времени выполнения
ch <- true
}
func main() {
var phones = [2]string{"foo", "bar"}
ch := make(chan bool) // канал
for {
fmt.Println("start request")
for _, phone := range phones{
go someRequest(phone, ch)
}
//ожидаем завершения всех каналов
for i:=0 ; i < len(phones); i++{
<-ch
}
fmt.Println("success")
}
}
Answer the question
In order to leave comments, you need to log in
You can create a channel for data that needs to be written to the database and goroutine to the station, inside each infinite loop. Goroutines constantly read each of their stations and write data to one channel that needs to be entered into the database. Another goroutine reads from this channel via range and writes data to the database.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question