Sobes.tech
Junior — Middle

Kuidas realiseerida mitme goroutine'i järjestikune täitmine andmevahetusega nende vahel?

sobes.tech AI

Vastus AI-lt

In Go, to execute multiple goroutines sequentially with data transfer between them, you can use the following methods:

  1. Channels — the main and most idiomatic way to transfer data between goroutines. You can create a channel through which one goroutine sends data, and the next receives and processes it, then passes it on.
ch1 := make(chan int)
ch2 := make(chan int)

// First goroutine
go func() {
    ch1 <- 42 // sending data
}()

// Second goroutine
go func() {
    val := <-ch1 // receiving data
    ch2 <- val * 2
}()

// Main goroutine receives the result
result := <-ch2
fmt.Println(result) // 84
  1. WaitGroup + channels — to control the completion of goroutines and the sequence.

  2. Data transfer via closures or synchronized structures — less common, but possible.

  3. Using context (context.Context) — for managing lifetime and cancellations, but not for direct data transfer.

Channels are the simplest and most reliable way to organize sequential processing with data transfer between goroutines.