package main

import (

var count int           		// 全局变量count
var rwlock sync.RWMutex       	// 全局读写锁 rwlock

func read(n int)  {
	fmt.Printf("读 goroutine %d 正在读取数据...\n", n)
	num := count
	fmt.Printf("读 goroutine %d 读取数据结束,读到 %d\n", n, num)
	defer rwlock.RUnlock()
func write(n int)  {
	fmt.Printf("写 goroutine %d 正在写数据...\n", n)
	num := rand.Intn(1000)
	count = num
	fmt.Printf("写 goroutine %d 写数据结束,写入新值 %d\n", n, num)
	defer rwlock.Unlock()
func main()  {

    for i:=0;i<5;i++{
    	go read(i+1)

	for i:=0;i<5;i++{
		go write(i+1)



已标记关键词 清除标记
<div class="post-text" itemprop="text"> <p>I've been using an RWLock for reads on a mysql database, but it appears that intermittently the following code locks the programs as it waits for a unlock?</p> <pre><code>// Returns string value from key in table specified, third parameter should be set to false if it shouldn't be case senstive. func (self *DBStore) GetString(table string, key string, vargs...interface{}) (output string) { defer func() { fmt.Println("GETSTRING Freeing Mutex!") }() self.mutex.RLock() fmt.Println("GETSTRING Got Mutex!") defer self.mutex.RUnlock() self.Get(table, key, &output, vargs...) return } // Retreive a value at key in table specified. func (self *DBStore) Get(table string, key string, output interface{}, vargs...interface{}) (found bool) { defer func() { fmt.Println("GET Freeing Mutex!") }() fmt.Println("Requesting Mutex") self.mutex.RLock() fmt.Println("GET Got Mutex!") defer self.mutex.RUnlock() </code></pre> <p>Now with the above, I can see that I really don't need to perform the RLock here and I can simply enough just remove it, but I was under the impression read locks shouldn't interfere with another read lock. Also it seems to be intermittent, and it usually takes me a few times of running the same thing before it reoccurs.</p> <p>Output of program is:</p> <pre><code>Requesting Mutex GET Got Mutex! GET Freeing Mutex! GETSTRING Got Mutex! Requesting Mutex </code></pre> <p>and then it just sits forever, locked. What am I missing here?</p> <p>Any info would be appreciated!</p> <p>go version go1.4 darwin/amd64</p> </div>
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页