Go में Concurrency

Go sync.Mutex

Stop goroutines from losing updates when they change the same value.

  • उन्नत
  • 4 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • Lock and Unlock
  • defer Unlock
  • Why the count is always right
4 goroutines x 1000 increments
  1. 1mu.Lock()one at a time
  2. 2count++safe update
  3. 3mu.Unlock()next goroutine
  4. 44000always

One goroutine at a time

When goroutines change the same variable at the same time, updates can be lost. A Mutex is a lock: only the goroutine that holds it may touch the data.

Lock waits until no other goroutine holds the lock, and defer Unlock releases it when the method returns. Without the mutex, count++ from four goroutines would lose updates. Four goroutines each add 1000, so the result is always 4000.

मुख्य बातें

  1. Lock waits until the mutex is free.
  2. defer Unlock releases it on return.
  3. Without a lock, count++ can lose updates.

चलने योग्य Go उदाहरण

Go
कोड चलाएँ →
main.go
package main

import (
	"fmt"
	"sync"
)

type Counter struct {
	mu    sync.Mutex
	count int
}

func (c *Counter) Increment() {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.count++
}

func (c *Counter) Value() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.count
}

func main() {
	counter := &Counter{}
	var wg sync.WaitGroup

	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 1000; j++ {
				counter.Increment()
			}
		}()
	}

	wg.Wait()
	fmt.Println("final count:", counter.Value())
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
final count: 4000

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Worker Pool →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज