programming

How to Create RW Mutex and Its Use in Golang

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.

type Counting struct {
	RWMutex sync.RWMutex
	TotalCount int
}

func (c *Counting) Add(amount int) {
	c.RWMutex.Lock()
	c.TotalCount = c.TotalCount + amount
	c.RWMutex.Unlock()
}

func (c *Counting) GetCount() int {
	c.RWMutex.RLock()
	count := c.TotalCount
	c.RWMutex.RUnlock()
	return count
}

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.

func main() {
	count := Counting{}
	for i := 0; i < 1000; i++ {
		go func() {
			count.Add(1)
			fmt.Println("count : ", count.GetCount())
		}()
	}
	time.Sleep(5 * time.Second)
	fmt.Println("Final Count : ", count.GetCount())
}

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.

count :  1
count :  30
..
..
count:  986
Count:  537
Final 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.**

comments powered by Disqus