fandingo
fandingo

Reputation: 1360

Go: How to Synchronize and Share Data

I'm writing a net/http server. My request handlers need access to some shared data that is updated by another go-routine. This go-routine keeps a single struct updated, and all of the net/http handlers need access to the same struct.

type MyData struct {
  Expiration time.Time
  A  string
  B  string
  C string
}

func update(data MyData) {
  go func() {
    for {
      if data.Expiration >= time.Now() {
        // set A, B, C
      }
      // sleep
    }
  }()
}

What's the best way to make a single, common MyData available to other go-routines? I was thinking a channel, but every reader of the channel should get the same MyData. The problem is that reading from a channel pops the item off the channel. I guess I'm looking for how to Peek() on the reader side, and Drain() on the writer side when it's time to update.

Upvotes: 2

Views: 865

Answers (1)

Marsel Novy
Marsel Novy

Reputation: 1817

Mutex based solution

type MyData struct {
    Expiration time.Time
    A  string
    B  string
    C string
}

type MutexedMyData struct {
    sync.RWMutex
    MyData MyData
}

var m = &MutexedMyData{}


func (m *MutexedMyData) Update(my_data MyData)  {
    m.Lock()
    m.MyData = my_data
    m.Unlock()
}

func (m *MutexedMyData) Read() MyData {
    u.RLock()
    value := m.MyData
    u.RUnlock()

    return value
}

Upvotes: 3

Related Questions