Last active
March 5, 2017 01:10
-
-
Save lucasrpb/590de0e68bd3ccad43c1006961db2596 to your computer and use it in GitHub Desktop.
vector_clock.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "time" | |
| ) | |
| type VectorClock struct { | |
| values map[string]int64 | |
| } | |
| func NewVectorClock() *VectorClock { | |
| return &VectorClock{make(map[string]int64)} | |
| } | |
| func(v *VectorClock) update(p string){ | |
| v.values[p] = time.Now().UnixNano() | |
| } | |
| func(v *VectorClock) merge(u *VectorClock){ | |
| for k, t1 := range v.values { | |
| t2 := u.values[k] | |
| if(t1 >= t2){ | |
| v.values[k] = t1 | |
| } else { | |
| v.values[k] = t2 | |
| } | |
| } | |
| } | |
| func(v *VectorClock) eq(u *VectorClock) bool { | |
| for k , t1 := range v.values { | |
| if(u.values[k] != t1) { | |
| return false | |
| } | |
| } | |
| return true | |
| } | |
| func(v *VectorClock) lte(u *VectorClock) bool { | |
| for k, t1 := range v.values { | |
| if(t1 > u.values[k]){ | |
| return false | |
| } | |
| } | |
| return true | |
| } | |
| /** | |
| * A and B can happen at the same time. If A and B are not concurrent and not equal and we want to know whether A occurred | |
| * before B, must exist some timestamp in A that is less the timestamp in the same position in B | |
| */ | |
| func(v *VectorClock) lt(u *VectorClock) bool { | |
| atLeastOneNotEqual := false | |
| for k, t1 := range v.values { | |
| t2 := u.values[k] | |
| if(t1 < t2){ | |
| atLeastOneNotEqual = true | |
| } else if(t1 > t2) { | |
| return false | |
| } | |
| } | |
| return atLeastOneNotEqual | |
| } | |
| /** | |
| * To events are concurrent when we cannot identify if at least one of the events happened before, i.e.: | |
| * there is at least one timestamp in A that is greater than a timestamp in the same position of B and vice-versa | |
| * (deadlock) | |
| */ | |
| func(v *VectorClock) isConcurrent(u *VectorClock) bool { | |
| // Verify if there's no causality in both directions A -> B and B -> A | |
| return !v.lt(u) && !u.lt(v) | |
| } | |
| func main() { | |
| v1 := NewVectorClock() | |
| v2 := NewVectorClock() | |
| v1.values = map[string]int64{"p1": 2, "p2": 4, "p3": 1} | |
| v2.values = map[string]int64{"p1": 3, "p2": 4, "p3": 1} | |
| fmt.Println(v1.isConcurrent(v2)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment