How to use Mutex in Go language to ensure data read and write correctness?

In Go language, the Mutex type in the sync package can be used to ensure the correctness of data reading and writing. The Mutex, short for mutual exclusion lock, provides two methods: Lock and Unlock, for locking and unlocking. The following is an example code that demonstrates how to use Mutex to ensure the correctness of data reading and writing.

package main

import (
	"fmt"
	"sync"
	"time"
)

type Counter struct {
	mu    sync.Mutex
	count int
}

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

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

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

	// 启动多个goroutine并发地对计数器进行增加操作
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			counter.Increment()
		}()
	}

	wg.Wait()

	// 读取计数器的值
	fmt.Println(counter.Read())
}

The Counter type in the code above contains a field mu of type sync.Mutex to protect read and write operations on the count field. The Increment method is used to increase the count, while the Read method is used to read the value of count.

In the Increment and Read methods, c.mu.Lock() is used to lock first, and c.mu.Unlock() is used to unlock at the end of the method. This ensures that only one goroutine can access the count field in the code block, thereby ensuring the correctness of data reading and writing.

In the main function, 100 concurrent goroutines are launched to increment the counter, which is then read. By using a Mutex to lock and unlock, there is no issue of data race when multiple goroutines concurrently increment the counter. The final value of the counter is 100, indicating that the correctness of data reading and writing has been guaranteed.

bannerAds