Skip to content

Instantly share code, notes, and snippets.

@mzdravkov mzdravkov/sync.go
Created Jan 30, 2016

Embed
What would you like to do?
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
for i := 0; i < 100; i++ {
go func(i int) {
fmt.Println(i, <-ch)
}(i)
}
time.Sleep(1000)
go func() {
ch <- 1
}()
go func() {
ch <- 2
}()
time.Sleep(1000)
}
@ironsmile

This comment has been minimized.

Copy link

commented Jan 30, 2016

Решението ти за синхронизация със sleep е доста непостоянно. Разгледай този пример:

package main

import (
    "fmt"
    "sync"
)

func main() {
    ch := make(chan int)
    start := make(chan struct{})
    var wg sync.WaitGroup

    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            <-start
            fmt.Println(i, <-ch)
        }(i)
    }   
    close(start)
    for i := 0; i < 100; i++ {
        ch <- i
    }   

    wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.