Table of Contents
Question content
Solution
Home Backend Development Golang Is replacing a mapped variable with a new mapped object thread safe?

Is replacing a mapped variable with a new mapped object thread safe?

Feb 10, 2024 pm 04:33 PM
concurrent access key value pair

Is replacing a mapped variable with a new mapped object thread safe?

php editor Apple is here to answer a common question: "Is it thread-safe to replace a mapping variable with a new mapping object?" Mapping variables are a common data structure. Used to store key-value pairs. In a multi-threaded environment, thread safety is an important consideration. Although using a new mapping object can avoid the problem of concurrent access, whether it is thread-safe still needs to be evaluated on a case-by-case basis. Next, we will explore this issue in depth to help readers better understand the relationship between thread safety and mapped objects.

Question content

I don't think it is thread-safe because the mapped object is larger than the machine word, and golang does not guarantee that it is thread-safe. But when I run the demo code using go run -race main.go it never reports an error. This may be the reason why threadsanitizer relies on runtime checks and assignment operations to find it difficult to satisfy thread unsafe conditions.

Here is the sample code:

package main

import (
    "fmt"
)

var m = make(map[int]bool)

func Read() {
    for {
        for k := range m {
            fmt.Println(k)
        }
    }
}

func Replace() {
    for {
        newM := make(map[int]bool, 10)
        for i := 0; i < 10; i++ {
            newM[i] = false
        }
        m = newM
    }
}

func main() {
    c := make(chan struct{})

    go Read()
    go Replace()

    <-c
}

Copy after login

So how do I modify the code to trigger concurrency errors? Or maybe I'm wrong and the code is thread safe?

Solution

There are a few points to note:

for k := range m {
Copy after login

Range expressions are evaluated once at the beginning of the for loop. So this operation will read m once (note, this means that if the code in the loop reallocates m, the loop will continue to iterate the original m, but If new elements are added or elements are removed from m, these will be detected by the loop), the loop itself will call fmt.println, which will consume most of the execution time in this goroutine . If you want to catch up on the game, delete it.

Second, you don't actually need to initialize the second map.

When you perform these operations and run the race detector, it may catch data races. As far as I'm concerned, it does.

The race detector complains about race when it detects race. So if it reports a match, then there is a match. If it's not reported, it doesn't mean there's no contest.

On my platform, the map variable itself is actually the same size as a machine word: it's just a pointer to the mapped structure. Therefore, writes to mapped variables are effectively atomic, i.e. you will not see partially allocated maps on this platform. However, this does not prevent contention since there is no guarantee when other goroutines will see this memory write.

In short, this is a competition. This is not because of the size of the map variable. To fix this problem, use a mutex.

The above is the detailed content of Is replacing a mapped variable with a new mapped object thread safe?. 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 AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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

Methods for ensuring thread safety of volatile variables in Java: Visibility: Ensure that modifications to volatile variables by one thread are immediately visible to other threads. Atomicity: Ensure that certain operations on volatile variables (such as writing, reading, and comparison exchanges) are indivisible and will not be interrupted by other threads.

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

Pitfalls in Go Language When Designing Distributed Systems Go is a popular language used for developing distributed systems. However, there are some pitfalls to be aware of when using Go, which can undermine the robustness, performance, and correctness of your system. This article will explore some common pitfalls and provide practical examples on how to avoid them. 1. Overuse of concurrency Go is a concurrency language that encourages developers to use goroutines to increase parallelism. However, excessive use of concurrency can lead to system instability because too many goroutines compete for resources and cause context switching overhead. Practical case: Excessive use of concurrency leads to service response delays and resource competition, which manifests as high CPU utilization and high garbage collection overhead.

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

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

Unit testing concurrent functions is critical as this helps ensure their correct behavior in a concurrent environment. Fundamental principles such as mutual exclusion, synchronization, and isolation must be considered when testing concurrent functions. Concurrent functions can be unit tested by simulating, testing race conditions, and verifying results.

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

DeepSeek: How to deal with the popular AI that is congested with servers? As a hot AI in 2025, DeepSeek is free and open source and has a performance comparable to the official version of OpenAIo1, which shows its popularity. However, high concurrency also brings the problem of server busyness. This article will analyze the reasons and provide coping strategies. DeepSeek web version entrance: https://www.deepseek.com/DeepSeek server busy reason: High concurrent access: DeepSeek's free and powerful features attract a large number of users to use at the same time, resulting in excessive server load. Cyber ​​Attack: It is reported that DeepSeek has an impact on the US financial industry.

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

In Java concurrent programming, race conditions and race conditions can lead to unpredictable behavior. A race condition occurs when multiple threads access shared data at the same time, resulting in inconsistent data states, which can be resolved by using locks for synchronization. A race condition is when multiple threads execute the same critical part of the code at the same time, leading to unexpected results. Atomic operations can be ensured by using atomic variables or locks.

PHP Redis caching applications and best practices PHP Redis caching applications and best practices May 04, 2024 am 08:33 AM

Redis is a high-performance key-value cache. The PHPRedis extension provides an API to interact with the Redis server. Use the following steps to connect to Redis, store and retrieve data: Connect: Use the Redis classes to connect to the server. Storage: Use the set method to set key-value pairs. Retrieval: Use the get method to obtain the value of the key.

How to use PHP functions to process JSON data? How to use PHP functions to process JSON data? May 04, 2024 pm 03:21 PM

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ​​of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

See all articles