


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 }
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 {
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Using JSON.parse() string to object is the safest and most efficient: make sure that strings comply with JSON specifications and avoid common errors. Use try...catch to handle exceptions to improve code robustness. Avoid using the eval() method, which has security risks. For huge JSON strings, chunked parsing or asynchronous parsing can be considered for optimizing performance.

How to distinguish between closing tabs and closing entire browser using JavaScript on your browser? During the daily use of the browser, users may...

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Yes, the URL requested by Vue Axios must be correct for the request to succeed. The format of url is: protocol, host name, resource path, optional query string. Common errors include missing protocols, misspellings, duplicate slashes, missing port numbers, and incorrect query string format. How to verify the correctness of the URL: enter manually in the browser address bar, use the online verification tool, or use the validateStatus option of Vue Axios in the request.

MySQL uses shared locks and exclusive locks to manage concurrency, providing three lock types: table locks, row locks and page locks. Row locks can improve concurrency, and use the FOR UPDATE statement to add exclusive locks to rows. Pessimistic locks assume conflicts, and optimistic locks judge the data through the version number. Common lock table problems manifest as slow querying, use the SHOW PROCESSLIST command to view the queries held by the lock. Optimization measures include selecting appropriate indexes, reducing transaction scope, batch operations, and optimizing SQL statements.

There are no shortcuts to learning Oracle databases. You need to understand database concepts, master SQL skills, and continuously improve through practice. First of all, we need to understand the storage and management mechanism of the database, master the basic concepts such as tables, rows, and columns, and constraints such as primary keys and foreign keys. Then, through practice, install the Oracle database, start practicing with simple SELECT statements, and gradually master various SQL statements and syntax. After that, you can learn advanced features such as PL/SQL, optimize SQL statements, and design an efficient database architecture to improve database efficiency and security.

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.
