search
HomeBackend DevelopmentGolangAbout Mutex in Go concurrent programming

The following is introduced to you by the golangtutorial column Go Mutex for concurrent programming, I hope it will be helpful to friends in need!

Friendly reminder: This article takes about 5 minutes and 45 seconds to read. Please give me more advice on any shortcomings. Thank you for reading.

Concurrent access problems will appear in the design of our more common large-scale projects. Concurrency is to solve the accuracy of data and ensure that the data in the same critical section can only be operated by one thread. It is used in daily life There are also many concurrent scenarios:

  • Counter: The counter result is inaccurate;
  • Second Kill System: Due to the large number of visits at the same time , resulting in oversold;
  • User account abnormality: account overdraft caused by payment at the same time;
  • buffer data abnormality: caused by updating buffer The data is messy.

The above are all problems of data accuracy caused by concurrency. The decisive solution is to use mutex lock, which is the Mutex concurrency primitive to be described in today's concurrent programming. .

Implementation mechanism

Mutex lock Mutex is a concurrency control mechanism established to avoid concurrency competition, in which there is the concept of "critical section".

In the process of concurrent programming, if some resources or variables in the program will be accessed or modified concurrently, in order to avoid data inaccuracies caused by concurrent access, this part of the program needs to be protected first, and then operated , remove the protection after the operation is completed, this part of the protected program is called critical section.

Use a mutex lock to limit the critical section to be held by only one thread at the same time. If the critical section is held by one thread at this time, then other threads want to enter this When the critical section is reached, it will fail or wait for the lock to be released. The thread holding this critical section will exit, and other threads will have the opportunity to obtain this critical section.

go mutex critical section diagram

Mutex is the most widely used synchronization primitive in the Go language, also known as concurrency primitive,Solution The purpose is to concurrently read and write shared resources to avoid data race problems.

Basic use

Mutex provides two methods, Lock and Unlock: to enter the critical section, use the Lock method to lock, and to exit the critical section, use The Unlock method releases the lock.

type Locker interface {
    Lock()
    Unlock()}func(m *Mutex)Lock()func(m *Mutex)Unlock()

When a goroutine calls the Lock method to acquire the lock, other goroutines will block on the Lock call until the goroutine currently acquiring the lock releases the lock.

The following is an example of a counter, which is performed by 100 goroutines to accumulate the counter, and the final output result is:

package mainimport (
    "fmt"
    "sync")func main() {
    var mu sync.Mutex
    countNum := 0

    // 确认辅助变量是否都执行完成
    var wg sync.WaitGroup    // wg 添加数目要和 创建的协程数量保持一致
    wg.Add(100)
    for i := 0; i <h2>
<span class="header-link octicon octicon-link"></span>Actual use</h2> <p>Many times Mutex is not used alone, but is used nested in a Struct as part of the structure. <strong>If the embedded struct has multiple fields, we generally put the Mutex in the field to be controlled. above, and then use spaces to separate the fields. </strong></p><p><strong>You can even encapsulate the logic of acquiring locks, releasing locks, and counting by one into a method. </strong></p><pre class="brush:php;toolbar:false">package mainimport (
    "fmt"
    "sync")// 线程安全的计数器type Counter struct {
    CounterType int
    Name        string

    mu    sync.Mutex
    count uint64}// 加一方法func (c *Counter) Incr() {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.count++}// 取数值方法 线程也需要受保护func (c *Counter) Count() uint64 {
    c.mu.Lock()
    defer c.mu.Unlock()
    return c.count}func main() {
    // 定义一个计数器
    var counter Counter    var wg sync.WaitGroup
    wg.Add(100)

    for i := 0; i <h2>
<span class="header-link octicon octicon-link"></span>Thinking Questions</h2><p>Q: You already know that if Mutex has been locked by a goroutine, other waiting goroutines can only wait forever. . So, after the lock is released, which of the waiting goroutines will get the Mutex first? </p><p>A: FIFO, first come first served strategy. In Go's goroutine scheduling, a queue is maintained to ensure the running of goroutine. When the goroutine that acquires the lock completes the operation of the critical section, it will be released. Lock, the goroutine ranked first in the queue will get the lock to operate the critical section. <span class="rm-link-color">                                                                                                                   </span></p>

The above is the detailed content of About Mutex in Go concurrent programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Golang vs. C  : Code Examples and Performance AnalysisGolang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AM

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

Is technology stack convergence just a process of technology stack selection?Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PM

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.