Table of Contents
Question content
Solution
Home Backend Development Golang Lock the map for concurrent access to the map

Lock the map for concurrent access to the map

Feb 09, 2024 am 11:06 AM
concurrent access

Lock the map for concurrent access to the map

php editor Baicao is here to introduce to you a very useful technique, which is to lock the map for concurrent access. This technique can help developers avoid conflicts and data errors when accessing the map concurrently. By using a locking mechanism, developers can ensure that each request is made in order and that no data clutter occurs. This is very important for developing map operations, especially when multiple users are accessing the map at the same time. Let’s take a look at how to implement this technique!

Question content

I have a map: map[string]map[string]*Struct and I need to read/write it in multiple Go routines.

What is the best way to achieve this? Mutex or RWMutex? And where to place it?

If I use RWMutex, should I Lock or RLock before performing operations involving reading and writing?

I tried using rwmutex in the root map, but I'm not sure if that's the best way to solve this problem.

I also tried "locking" before reading and writing, but sometimes I get "concurrent writes" panics.

Solution

You can use RWLock. If the operation involves writing (whether it is reading or writing only), you need to use Lock, if it only involves reading, RLock/RUnlock.

Lock can also be considered an exclusive lock. RLock, on the other hand, is non-exclusive. An RLock can be acquired even if the RWMutex is locked for reading, but goroutine execution will be blocked if the resource is locked exclusively by the Lock method:

1

a blocked Lock call excludes new readers from acquiring the lock

Copy after login

On the other hand, the Lock method blocks goroutine execution until all readers and writers unlock the resource (using the RUnlock/Unlock method). Lock is exclusive because only one goroutine can access the resource (whether reading or writing) until the Unlock method is called.

Typical method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

package main

 

import (

    "fmt"

    "sync"

)

 

type SomeStruct struct {

    someInfo string

}

 

type ConcurrentStruct struct {

    mu   sync.RWMutex

    data map[string]map[string]*SomeStruct

}

 

func New() *ConcurrentStruct {

    return &ConcurrentStruct{

        data: make(map[string]map[string]*SomeStruct),

    }

}

 

func (cs *ConcurrentStruct) Set(key1, key2 string, val SomeStruct) {

    cs.mu.Lock()

    defer cs.mu.Unlock()

 

    if _, ok := cs.data[key1]; !ok {

        cs.data[key1] = make(map[string]*SomeStruct)

    }

    cs.data[key1][key2] = &val

}

 

func (cs *ConcurrentStruct) Get(key1, key2 string) (val *SomeStruct, ok bool) {

    cs.mu.RLock()

    defer cs.mu.RUnlock()

 

    if _, ok := cs.data[key1]; ok {

        val, ok := cs.data[key1][key2]

        return val, ok

    }

 

    return nil, false

}

 

func main() {

    cs := New()

    cs.Set("a", "b", SomeStruct{"Hello, World!"})

 

    if _, ok := cs.Get("a", "c"); !ok {

        fmt.Printf("key1=a, key2=c, not found\n")

    }

 

    if s, ok := cs.Get("a", "b"); ok {

        fmt.Printf("key1=a, key2=b, found: %v\n", s)

    }

}

Copy after login

The above is the detailed content of Lock the map for concurrent access to the map. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to ensure thread safety of volatile variables in Java functions? How to ensure thread safety of volatile variables in Java functions? May 04, 2024 am 10:15 AM

How to ensure thread safety of volatile variables in Java functions?

What pitfalls should we pay attention to when designing distributed systems with Golang technology? What pitfalls should we pay attention to when designing distributed systems with Golang technology? May 07, 2024 pm 12:39 PM

What pitfalls should we pay attention to when designing distributed systems with Golang technology?

How to return pointer in golang? How to return pointer in golang? Apr 23, 2024 pm 02:09 PM

How to return pointer in golang?

Locking and synchronization mechanism of C++ functions in concurrent programming? Locking and synchronization mechanism of C++ functions in concurrent programming? Apr 27, 2024 am 11:21 AM

Locking and synchronization mechanism of C++ functions in concurrent programming?

How to solve the problem of busy servers for deepseek How to solve the problem of busy servers for deepseek Mar 12, 2025 pm 01:39 PM

How to solve the problem of busy servers for deepseek

A guide to unit testing Go concurrent functions A guide to unit testing Go concurrent functions May 03, 2024 am 10:54 AM

A guide to unit testing Go concurrent functions

How to deal with race conditions and race conditions in Java concurrent programming? How to deal with race conditions and race conditions in Java concurrent programming? May 08, 2024 pm 04:33 PM

How to deal with race conditions and race conditions in Java concurrent programming?

How to implement lock-free data structures in Java concurrent programming? How to implement lock-free data structures in Java concurrent programming? May 02, 2024 am 10:21 AM

How to implement lock-free data structures in Java concurrent programming?

See all articles