其他分享
首页 > 其他分享> > Golang实现线程安全的Map

Golang实现线程安全的Map

作者:互联网

1、使用互斥锁实现

2、Set\Get入口加锁

package main

import (
    "fmt"
    "sync"
    "time"
)

var wg sync.WaitGroup

// ExcuteResult 执行结果集
type ExcuteResult struct {
    data map[string]interface{}
    mux  *sync.Mutex
}

// NewExcuteResult 创建一个执行结果集
func NewExcuteResult(data map[string]interface{}) *ExcuteResult {
    return &ExcuteResult{
        data: data,
        mux:  &sync.Mutex{},
    }
}

// Get 获取结果集的元素-加锁保证并发安全
func (d *ExcuteResult) Get(key string) interface{} {
    d.mux.Lock()
    defer d.mux.Unlock()
    return d.data[key]
}

// Set 设置结果集的元素值-加锁保证并发安全
func (d *ExcuteResult) Set(key string, value interface{}) {
    d.mux.Lock()
    defer d.mux.Unlock()
    d.data[key] = value
}

func main()  {
    excelData := []string{"1","2","3","4","5","6","7","8","9","10"}
    dict := NewExcuteResult(map[string]interface{}{})
    for _,v := range excelData{
        wg.Add(1)
        go readExcel(v,dict)
        // 通过管道阻塞协程执行
        // <-ch
    }
    // 主协程让出时间片 - 但是不会一直等待-如果子协程sleep时间过于长也会直接往下执行
    // runtime.Gosched()
    wg.Wait()
    fmt.Println("主协程结束")
    // 从管道拿数据
    fmt.Println(dict)
    
}

func readExcel(v string,d *ExcuteResult)(result string){
    fmt.Println(v)
    time.Sleep(time.Second)
    // 给管道写数据
    // ch <- v
    d.Set(v,v)
    wg.Done()
    return v
}

 3、互斥锁 - sync.Mutex \  读写锁 sync.RWMuTex

 

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
  TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back

标签:Map,string,sync,mux,Golang,线程,ExcuteResult,interface,data
来源: https://www.cnblogs.com/xuweiqiang/p/16389979.html