Basic Concepts
ACID Principle
-
Atomicity: the entire transaction happens at once, or doesn't happen at all
-
Consistency: database must be consistent before and after transactions
-
Isoluation: multiple transactions can occur independently without inteference
-
Durability: changes of a successful transaction occurs even if the system failure occurs
C10K problem?
- the challenge of designing and implementing a server that can efficiently handle a large number of concurrent client connections, specifically 10,000.
- solution:
- asynchronous I/O
- Non-Blocking I/O
- Efficient Data Structures
- Connection Pooling
Mutex lock
What is it
mutual exclusion
a synchronization primitive used in concurrent programming to ensure that only one thread can access a shared resource at a time
How it works
Locking:
a thread that needs to access a sahred resource acquires the mutex lock
if the mutex is already locked by another thread, the requesting thread is blocked until the lock is released
Critical Section
once the lock is acquired, the thread enters a critical section, where it accesses and modifies the shared resource
Unlocking
After the thread finishes with the shared resource, it releases the mutex lock
Key Points:
Atomic: mutexes ensures that operations on shared resources are atomic, meaning they are indivisible and cannot be interupted by other threads
Deadlocks: Improper use of mutexes can lead to deadlocks, where two or more threads are waiting for each other to release locks, resulting in a stalemate
Starvation: In some cases a thread may be repeatedly denied access to a shared resource, even if it's available, due to other threads continuously acquiring and releasing the lock.
Example:
package main
import (
"fmt"
"sync"
)
var counter int
var mu sync.Mutex
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
func main() {
for i:=0; i<1000; i++ {
go increment()
}
// wait for al lgoroutines to finish
fmt.Println("Final counter value: ", counter)
}