• Go语言锁的使用


    线程同步

    a. import(“sync”)
    
    
    b. 互斥锁, var mu sync.Mutex
    
    
    c. 读写锁, var mu sync.RWMutex
    
    package main
    
    import (
    	"fmt"
    	"math/rand"
    	"sync"
    	"sync/atomic"
    	"time"
    )
    
    var lock sync.Mutex       //互斥锁
    var rwLock sync.RWMutex  // 读写锁
    
    func testMap() {
    	var a map[int]int
    	a = make(map[int]int, 5)
    
    	a[8] = 10
    	a[3] = 10
    	a[2] = 10
    	a[1] = 10
    	a[18] = 10
    
    	for i := 0; i < 2; i++ {
    		go func(b map[int]int) {
    			lock.Lock()
    			b[8] = rand.Intn(100)
    			lock.Unlock()
    		}(a)
    	}
    
    	lock.Lock()
    	fmt.Println(a)
    	lock.Unlock()
    
    	time.Sleep(time.Second)
    }
    
    func testRWLock() {
    	var a map[int]int
    	a = make(map[int]int, 5)
    	var count int32
    	a[8] = 10
    	a[3] = 10
    	a[2] = 10
    	a[1] = 10
    	a[18] = 10
    
    	for i := 0; i < 2; i++ {
    		go func(b map[int]int) {
    			//rwLock.Lock()
    			lock.Lock()
    			b[8] = rand.Intn(100)
    			time.Sleep(10 * time.Millisecond)
    			lock.Unlock()
    			//rwLock.Unlock()
    		}(a)
    	}
    
    	for i := 0; i < 100; i++ {
    		go func(b map[int]int) {
    			for {
    				lock.Lock()
    				//rwLock.RLock()
    				time.Sleep(time.Millisecond)
    				//fmt.Println(a)
    				//rwLock.RUnlock()
    				lock.Unlock()
    				atomic.AddInt32(&count, 1)
    			}
    		}(a)
    	}
    	time.Sleep(time.Second * 3)
    	fmt.Println(atomic.LoadInt32(&count))
    }
    
    func main() {
    	//testMap()
    	testRWLock()
    }
      
    

      

      

      

    I can feel you forgetting me。。 有一种默契叫做我不理你,你就不理我

  • 相关阅读:
    flask 知识积累
    python中下划线
    pipenv知识积累
    shell知识积累
    AttributeError: type object 'testClass' has no attribute 'testMothod'
    python知识积累
    补全爬取的url
    linux 的基本命令
    Python里的拷贝
    关于第一次java课的感想
  • 原文地址:https://www.cnblogs.com/weidaijie/p/11447789.html
Copyright © 2020-2023  润新知