<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                GO 里面 MAP 如何實現 key 不存在 get 操作等待 直到 key 存在或者超時,保證并發安全,且需要實現以下接口: ~~~go type sp interface { Out(key string, val interface{}) //存入key /val,如果該key讀取的goroutine掛起,則喚醒。此方法不會阻塞,時刻都可以立即執行并返回 Rd(key string, timeout time.Duration) interface{} //讀取一個key,如果key不存在阻塞,等待key存在或者超時 } ~~~ **解析:** 看到阻塞協程第一個想到的就是`channel`,題目中要求并發安全,那么必須用鎖,還要實現多個`goroutine`讀的時候如果值不存在則阻塞,直到寫入值,那么每個鍵值需要有一個阻塞`goroutine`的`channel`。 實現如下: ~~~ type Map struct { c map[string]*entry rmx *sync.RWMutex } type entry struct { ch chan struct{} value interface{} isExist bool } func (m *Map) Out(key string, val interface{}) { m.rmx.Lock() defer m.rmx.Unlock() if e, ok := m.c[key]; ok { e.value = val e.isExist = true close(e.ch) } else { e = &entry{ch: make(chan struct{}), isExist: true,value:val} m.c[key] = e close(e.ch) } } func (m *Map) Rd(key string, timeout time.Duration) interface{} { m.rmx.Lock() if e, ok := m.c[key]; ok && e.isExist { m.rmx.Unlock() return e.value } else if !ok { e = &entry{ch: make(chan struct{}), isExist: false} m.c[key] = e m.rmx.Unlock() fmt.Println("協程阻塞 -> ", key) select { case <-e.ch: return e.value case <-time.After(timeout): fmt.Println("協程超時 -> ", key) return nil } } else { m.rmx.Unlock() fmt.Println("協程阻塞 -> ", key) select { case <-e.ch: return e.value case <-time.After(timeout): fmt.Println("協程超時 -> ", key) return nil } } } ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看