01-pessimistic-locking

command
v0.0.0-...-6054030 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2024 License: MIT Imports: 2 Imported by: 0

README

Pessimitic Locking in GO

Running the following code on threads will give you inconsistent results.

func incCount(){
	count++;
	wg.Done()
}

func doCount(){
	for i:=0; i < 1000000; i++{
		wg.Add(1)
		go incCount()
	}
}

Reason:
Count++ (increment operation) is not atomic in nature. Micro-operations in registers

  1. movl %rdi, %tmp LOAD
  2. addl $1, %tmp ADD
  3. movl %tmp, %rdi STORE

Solution:
Lock and Unlock the operation (count++) using Mutex, so that only one thread runs the operation at a time.

var mu sync.Mutex

mu.Lock()
count++;
mu.Unlock()
Reference:

Pessimitic Locking with Mutex

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL