Advertisement
cwchen

[Go] Using mutex.

Nov 28th, 2017
1,066
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.38 KB | None | 0 0
  1. package vector
  2.  
  3. import (
  4.     "sync"
  5. )
  6.  
  7. type IVector interface {
  8.     Len() int
  9.     GetAt(int) float64
  10.     SetAt(int, float64)
  11. }
  12.  
  13. type Vector struct {
  14.     sync.RWMutex
  15.     vec []float64
  16. }
  17.  
  18. func New(args ...float64) IVector {
  19.     v := new(Vector)
  20.     v.vec = make([]float64, len(args))
  21.  
  22.     for i, e := range args {
  23.         v.SetAt(i, e)
  24.  
  25.     }
  26.  
  27.     return v
  28. }
  29.  
  30. // The length of the vector
  31. func (v *Vector) Len() int {
  32.     return len(v.vec)
  33. }
  34.  
  35. // Getter
  36. func (v *Vector) GetAt(i int) float64 {
  37.     if i < 0 || i >= v.Len() {
  38.         panic("Index out of range")
  39.     }
  40.  
  41.     return v.vec[i]
  42. }
  43.  
  44. // Setter
  45. func (v *Vector) SetAt(i int, data float64) {
  46.     if i < 0 || i >= v.Len() {
  47.         panic("Index out of range")
  48.     }
  49.  
  50.     v.Lock()
  51.     v.vec[i] = data
  52.     v.Unlock()
  53. }
  54.  
  55. / Vector algebra delegating to function object.
  56. // This method delegates vector algebra to function object set by users, making
  57. // it faster then these methods relying on reflection.
  58. func Apply(v1 IVector, v2 IVector, f func(float64, float64) float64) IVector {
  59.     _len := v1.Len()
  60.  
  61.     if !(_len == v2.Len()) {
  62.         panic("Unequal vector size")
  63.     }
  64.  
  65.     out := WithSize(_len)
  66.  
  67.     var wg sync.WaitGroup
  68.  
  69.     for i := 0; i < _len; i++ {
  70.         wg.Add(1)
  71.  
  72.         go func(v1 IVector, v2 IVector, out IVector, f func(float64, float64) float64, i int) {
  73.             defer wg.Done()
  74.  
  75.             out.SetAt(i, f(v1.GetAt(i), v2.GetAt(i)))
  76.         }(v1, v2, out, f, i)
  77.     }
  78.  
  79.     wg.Wait()
  80.  
  81.     return out
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement