Created
October 20, 2016 12:45
-
-
Save s4l1h/6b7b5e9d8dff1bc438f3c33a1c772123 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package main | |
| import ( | |
| "fmt" | |
| "sync" | |
| ) | |
| // Hit objemiz | |
| type Hit struct { | |
| count int | |
| sync.Mutex // Embeding olarak ekleyelim. | |
| } | |
| // goroutines'lerin çalışmasını ve işlemlerini bitirmelerini garantilemek için | |
| var wg sync.WaitGroup | |
| func main() { | |
| // Bir tane hit Objesi oluşturalım | |
| hit := &Hit{} | |
| // Toplam Artması gereken sayı.. | |
| count := 10000 | |
| // for döngümüz | |
| for i := 0; i < count; i++ { | |
| wg.Add(1) // 1 adet ekleyelim | |
| // anonymous bir fonksiyon oluşturup go keywordu ile goroutine çalışmasını sağlayalım | |
| go func(hit *Hit) { // fonksiyonun Hit objesinin pointer'ını almak zorunda | |
| hit.Lock() // Diğer goroutines'lerin erişmesini engelleyelim. | |
| hit.count++ // Sayıyı bir arttıralım | |
| hit.Unlock() // İşlem bittikten sonra erişim engelini kaldıralım | |
| wg.Done() // İşlem bitince wg DONE | |
| }(hit) // Fonksiyona Hit objesinin pointeri parametre olarak gönderiliyor. | |
| } | |
| wg.Wait() // tüm goroutines'ler bitinceye kadar kodu blokla | |
| fmt.Println("Olması Gereken", count, "\nŞimdi Elimizdeki ", hit.count, "\nKayıp", count-hit.count) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment