Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
14 Jun 2023 · 3 min read ·Article 103 / 119
Go

How to Create RW Mutex and Its Use in Golang

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Introduction to Sync.RWMutex

After we have learned Introduction and Creation of `Mutex` in the previous post, then we will continue to the next stage which is the introduction of RWMutex. Now what is the difference with the previous one?

The difference is more about the usage of the Mutex. Mutex is usually used only for one time in the sense that when setting a variable, while if we use RWMutex it is used for cases where we want to lock not only the process of changing data (write), but also locking against reading (read) the data.

In this case, we could have actually used Mutex but it would be a struggle between reading and changing data, so Golang provides struct sync.RWMutex (Read Write Mutex) to handle this problem which has two locks, namely locking for reading and locking for writing.

Code Implementation of sync.RWMutex

This time we will change the code in the previous post to be as below. The first thing we need to change is to create a struct for the needs of reading and changing data from variables in the struct.

go
 1type Counting struct {
 2	RWMutex sync.RWMutex
 3	TotalCount int
 4}
 5
 6func (c *Counting) Add(amount int) {
 7	c.RWMutex.Lock()
 8	c.TotalCount = c.TotalCount + amount
 9	c.RWMutex.Unlock()
10}
11
12func (c *Counting) GetCount() int {
13	c.RWMutex.RLock()
14	count := c.TotalCount
15	c.RWMutex.RUnlock()
16	return count
17}
After that, we also create a main function that calls the function to change and read the variables from the struct that we have created above. Here is the main function that we have changed.
go
 1func main() {
 2	count := Counting{}
 3	for i := 0; i < 1000; i++ {
 4		go func() {
 5			count.Add(1)
 6			fmt.Println("count : ", count.GetCount())
 7		}()
 8	}
 9	time.Sleep(5 * time.Second)
10	fmt.Println("Final Count : ", count.GetCount())
11}
Then the result of the code when we run it will be the same as finding 1000 count data. In this case, the implementation is the same as the previous Mutex but we need to read the data while running the add data process so we need to use RWMutex.
bash
1count :  1
2count :  30
3..
4..
5count:  986
6Count:  537
7Final Count :  1000

Conclusion

RWMutex and Mutex in its needs are the same, which is used for locking and unlocking process conditions where we will read and write to one variable so as not to fight each other if we use goroutines which access simultaneously. In this case, from several sources of articles that the author has read, it turns out that there is a downside to using RWMutex, namely in terms of performance being slower because of the use of locking which requires a longer process.**

Related Articles

💬 Comments