Home > Articles

This chapter is from the book

This chapter is from the book

Synchronizing Access with a Mutex

When you run tests with the -race flag, Go’s built-in race detector can help you find data races in your code. In Listing 13.30, for example, tests that pass normally fail when run with the race detector. The failure message lists the data race found and where the reads and writes occur in our code.

Listing 13.30 Detecting Race Conditions in Tests
$ go test -v -race

=== RUN   Test_Mutex
=== PAUSE Test_Mutex
=== CONT  Test_Mutex
--- PASS: Test_Mutex (0.00s)
PASS
==================
WARNING: DATA RACE
Read at 0x00c00019e3f0 by goroutine 9:
  runtime.mapdelete()
      /usr/local/go/src/runtime/map.go:695 +0x46c
  demo.Test_Mutex.func2()
      ./demo_test.go:46 +0x50

Previous write at 0x00c00019e3f0 by goroutine 8:
  runtime.mapaccess2_fast64()
      /usr/local/go/src/runtime/map_fast64.go:53 +0x1cc
  demo.Test_Mutex.func1()
      ./demo_test.go:32 +0x50

Goroutine 9 (running) created at:
  demo.Test_Mutex()
      ./demo_test.go:43 +0x188
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1439 +0x18c
  testing.(*T).Run.func1()
      /usr/local/go/src/testing/testing.go:1486 +0x44

Goroutine 8 (finished) created at:
  demo.Test_Mutex()
      ./demo_test.go:28 +0x124
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:1439 +0x18c
  testing.(*T).Run.func1()
      /usr/local/go/src/testing/testing.go:1486 +0x44
==================
0: true
2: true
4: true
7: true
9: true
1: true
3: true
5: true
6: true
8: true
Found 1 data race(s)
exit status 66
FAIL    demo    0.862s

Go Version: go1.19

In the test in Listing 13.31, we have two different goroutines. The first is modifying a shared resource—in this case, a map. The second goroutine is ranging over the map and printing out the map’s values.

In order for us to be able to fix this race condition, we need to be able to synchronize access to the shared resource.

Listing 13.31 Two Goroutines Accessing a Shared Map
// launch a goroutine to
// read data from the map
go func() {
    // loop through the map
    // and print the keys/values
    for k, v := range data {
        fmt.Printf("%d: %v\n", k, v)
    }
}()

// launch a goroutine to
// put data in the map
go func() {
    for i := 0; i < 10; i++ {

        // loop putting data in the map
        data[i] = true
    }

    // cancel the context
    cancel()
}()

Locker

To synchronize access to the shared resource, we need to be able to lock access to the resource. By locking a shared resource, we can ensure that only one goroutine at a time can access the resource and that the resource is not modified by another goroutine while it is locked.

The sync.Locker16 interface, Listing 13.32, defines the methods that a type must implement to be able to lock and unlock a shared resource.

Listing 13.32 The sync.Locker Interface
$ go doc sync.Locker

package sync // import "sync"

type Locker interface {
        Lock()
        Unlock()
}
    A Locker represents an object that can be locked and unlocked.

Go Version: go1.19

Locker Methods

You can use the sync.Locker.Lock17 method, Listing 13.33, to lock the shared resource. Once a resource is locked, no other goroutine can access the resource until it is unlocked.

Listing 13.33 The sync.Locker.Lock Method
$ go doc sync.Mutex.Lock

package sync // import "sync"

func (m *Mutex) Lock()
    Lock locks m. If the lock is already in use, the calling goroutine blocks
    arrow.jpguntil the mutex is available.

Go Version: go1.19

You can use the sync.Locker.Unlock18 method, Listing 13.34, to unlock the shared resource. Once a resource is unlocked, other goroutines can access the resource.

Listing 13.34 The sync.Locker.Unlock Method
$ go doc sync.Mutex.Unlock

package sync // import "sync"

func (m *Mutex) Unlock()
    Unlock unlocks m. It is a run-time error if m is not locked on entry to
    arrow.jpgUnlock.

    A locked Mutex is not associated with a particular goroutine. It is
    arrow.jpgallowed for one goroutine to lock a Mutex and then arrange for another
    arrow.jpggoroutine to unlock it.

Go Version: go1.19

Using a Mutex

The most basic mutex available in Go is the sync.Mutex type, Listing 13.35. The sync.Mutex uses a basic binary semaphore lock. This means that only one goroutine can access the resource at a time.

Listing 13.35 The sync.Mutex Type
$ go doc sync.Mutex

package sync // import "sync"

type Mutex struct {
        // Has unexported fields.
}
    A Mutex is a mutual exclusion lock. The zero value for a Mutex is an
    arrow.jpgunlocked mutex.

    A Mutex must not be copied after first use.

func (m *Mutex) Lock()
func (m *Mutex) TryLock() bool
func (m *Mutex) Unlock()

Go Version: go1.19

To use a sync.Mutex, you need to wrap the areas of code that you want to synchronize access to by first locking the sync.Mutex and then unlocking it. For example, in the second goroutine in Listing 13.36, a mutex is being used to lock access around writing values into the data map.

Listing 13.36 Locking Resources with a sync.Mutex
// launch a goroutine to
// read data from the map
go func() {
    // lock the mutex
    mu.Lock()

    // loop through the map
    // and print the keys/values
    for k, v := range data {
        fmt.Printf("%d: %v\n", k, v)
    }

    // unlock the mutex
    mu.Unlock()
}()

// launch a goroutine to
// put data in the map
go func() {

    for i := 0; i < 10; i++ {
        // lock the mutex
        mu.Lock()

        // loop putting data in the map
        data[i] = true

        // unlock the mutex
        mu.Unlock()
    }

    // cancel the context
    cancel()
}()

By locking access to the shared resource, you can ensure that only one goroutine at a time can access the resource. Our test output, Listing 13.37, confirms that the shared resource is only accessed by one goroutine at a time with a successful exit.

Listing 13.37 Passing Race Detector Tests
$ go test -v -race

=== RUN   Test_Mutex
=== PAUSE Test_Mutex
=== CONT  Test_Mutex
9: true
--- PASS: Test_Mutex (0.00s)
0: true
2: true
5: true
8: true
7: true
1: true
PASS
3: true
4: true
6: true
ok      demo    0.810s

Go Version: go1.19

RWMutex

Often, applications read a shared resource instead of writing to them. The sync.Mutex is a very heavy-weight locking mechanism. Access to a shared resource, whether it be a read or write, is blocked until the resource is unlocked. Only one goroutine can access a shared resource at a time.

When you want to be able to both read and write to a shared resource, you need to use a sync.RWMutex, Listing 13.38. The sync.RWMutex is a lighter-weight locking mechanism. A sync.RWMutex can allow many goroutines to read from the resource at the same time, but only one goroutine can write to the resource at a time.

Listing 13.38 The sync.RWMutex Type
$ go doc sync.RWMutex

package sync // import "sync"

type RWMutex struct {
        // Has unexported fields.
}

    A RWMutex is a reader/writer mutual exclusion lock. The lock can be held
    arrow.jpgby an arbitrary number of readers or a single writer. The zero value for
    arrow.jpga RWMutex is an unlocked mutex.

    A RWMutex must not be copied after first use.

    If a goroutine holds a RWMutex for reading and another goroutine might
    arrow.jpgcall Lock, no goroutine should expect to be able to acquire a read lock
    arrow.jpguntil the initial read lock is released. In particular, this prohibits
    arrow.jpgrecursive read locking. This is to ensure that the lock eventually
    arrow.jpgbecomes available; a blocked Lock call excludes new readers from
    arrow.jpgacquiring the lock.

func (rw *RWMutex) Lock()
func (rw *RWMutex) RLock()
func (rw *RWMutex) RLocker() Locker
func (rw *RWMutex) RUnlock()
func (rw *RWMutex) TryLock() bool
func (rw *RWMutex) TryRLock() bool
func (rw *RWMutex) Unlock()

Go Version: go1.19

The sync.RWMutex offers two additional methods beyond those of the sync.Locker interface. You can use the sync.RWMutex.Rlock19 and sync.RWMutex.RUnlock20 methods to lock the resource for reading. The sync.RWMutex.Lock21 and sync.RWMutex.Unlock22 methods are used to lock the resource across all goroutines for writing.

In Listing 13.39, we update the goroutine that is reading the resource to use the sync.RWMutex.Rlock method instead of the sync.Mutex.Lock method. This will allow for many goroutines to read from the resource at the same time.

Listing 13.39 Using a sync.RWMutex
// launch a goroutine to
// read data from the map
go func() {
    // lock the mutex
    mu.RLock()

    // loop through the map
    // and print the keys/values
    for k, v := range data {
        fmt.Printf("%d: %v\n", k, v)
    }

    // unlock the mutex
    mu.RUnlock()
}()

$ go test -v -race

=== RUN   Test_RWMutex
=== PAUSE Test_RWMutex
=== CONT  Test_RWMutex
4: true
5: true
6: true
--- PASS: Test_RWMutex (0.00s)
7: true
9: true
0: true
1: true
PASS
8: true
2: true
3: true
ok      demo    0.917s

Go Version: go1.19

The tests in Listing 13.39 continue to pass, but the performance of the program is improved by allowing multiple goroutines to read from the shared resource instead of arbitrarily locking all goroutines all at once.

Improper Usage

When using either sync.Mutex or sync.RWMutex, you must take care in making sure to lock and unlock in the proper order.

Consider Listing 13.40. We have a sync.Mutex, and we attempt to call sync.Mutex.Lock twice.

Listing 13.40 Attempting to Lock a sync.Mutex Twice
func Test_Mutex_Locks(t *testing.T) {
    t.Parallel()

    // create a new mutex
    var mu sync.Mutex

    // lock the mutex
    mu.Lock()

    fmt.Println("locked. locking again.")

    // try to lock the mutex again
    // this will block/deadlock
    // because the mutex is already locked
    // and the lock was not released
    mu.Lock()

    fmt.Println("unlocked twice")
}

The result is the program will deadlock and crash, as shown in Listing 13.41. The reason is that a call to sync.Mutex.Lock blocks until the sync.Mutex.Unlock method is called. Because we have already locked the sync.Mutex, the second call to sync.Mutex.Lock blocks indefinitely because it is never unlocked.

Listing 13.41 A Panic while Trying to Unlock an Already-Unlocked sync.Mutex
$ go test -v -timeout 10ms

=== RUN   Test_Mutex_Locks
=== PAUSE Test_Mutex_Locks
=== CONT  Test_Mutex_Locks
locked. locking again.
panic: test timed out after 10ms

goroutine 33 [running]:
testing.(*M).startAlarm.func1()
        /usr/local/go/src/testing/testing.go:2029 +0x8c
created by time.goFunc
        /usr/local/go/src/time/sleep.go:176 +0x3c
goroutine 1 [chan receive]:
testing.tRunner.func1()
        /usr/local/go/src/testing/testing.go:1405 +0x45c
testing.tRunner(0x140001361a0, 0x1400010fcb8)
        /usr/local/go/src/testing/testing.go:1445 +0x14c
testing.runTests(0x1400001e1e0?, {0x100ec9ea0, 0x1, 0x1},
arrow.jpg{0xe00000000000000?, 0x100cf5218?, 0x100ed2640?})
        /usr/local/go/src/testing/testing.go:1837 +0x3f0

testing.(*M).Run(0x1400001e1e0)
        /usr/local/go/src/testing/testing.go:1719 +0x500
main.main()
        _testmain.go:47 +0x1d0

goroutine 4 [semacquire]:
sync.runtime_SemacquireMutex(0x1400000e018?, 0x20?, 0x17?)
        /usr/local/go/src/runtime/sema.go:71 +0x28
sync.(*Mutex).lockSlow(0x14000012140)
        /usr/local/go/src/sync/mutex.go:162 +0x180
sync.(*Mutex).Lock(...)
        /usr/local/go/src/sync/mutex.go:81
demo.Test_Mutex_Locks(0x0?)
        ./demo_test.go:25 +0x130
testing.tRunner(0x14000136340, 0x100e25298)
        /usr/local/go/src/testing/testing.go:1439 +0x110
created by testing.(*T).Run
        /usr/local/go/src/testing/testing.go:1486 +0x300
exit status 2
FAIL    demo    0.527s

Go Version: go1.19

Worse than a deadlock caused by waiting for a lock that will never be unlocked is unlocking a lock that has not been locked.

In Listing 13.42, the result is a fatal error that crashes the application. The reason is that we have not locked the sync.Mutex before attempting to unlock it.

Listing 13.42 A Panic while Trying to Unlock an Unlocked sync.Mutex
func Test_Mutex_Unlock(t *testing.T) {
    t.Parallel()

    // create a new mutex
    var mu sync.Mutex

    // unlock the mutex
    mu.Unlock()
}

$ go test -v

=== RUN   Test_Mutex_Unlock
=== PAUSE Test_Mutex_Unlock
=== CONT  Test_Mutex_Unlock
fatal error: sync: unlock of unlocked mutex

goroutine 18 [running]:
runtime.throw(0x104573b02?, 0x1400005af18?)
        /usr/local/go/src/runtime/panic.go:992 +0x50 fp=0x1400005aee0
        arrow.jpgsp=0x1400005aeb0 pc=0x1044ba9a0
sync.throw(0x104573b02?, 0x1045b6260?)
        /usr/local/go/src/runtime/panic.go:978 +0x24 fp=0x1400005af00
        arrow.jpgsp=0x1400005aee0 pc=0x1044e5664
sync.(*Mutex).unlockSlow(0x140001280b0, 0xffffffff)
        /usr/local/go/src/sync/mutex.go:220 +0x3c fp=0x1400005af30
        arrow.jpgsp=0x1400005af00 pc=0x1044ef44c
sync.(*Mutex).Unlock(...)
        /usr/local/go/src/sync/mutex.go:214
demo.Test_Mutex_Unlock(0x0?)
        ./demo_test.go:16 +0x74 fp=0x1400005af60 sp=0x1400005af30
        arrow.jpgpc=0x10456d794
testing.tRunner(0x1400010b380, 0x1045c9298)
        /usr/local/go/src/testing/testing.go:1439 +0x110 fp=0x1400005afb0
        arrow.jpgsp=0x1400005af60 pc=0x104537660
testing.(*T).Run.func1()
        /usr/local/go/src/testing/testing.go:1486 +0x30 fp=0x1400005afd0
        arrow.jpgsp=0x1400005afb0 pc=0x1045383d0
runtime.goexit()
        /usr/local/go/src/runtime/asm_arm64.s:1263 +0x4 fp=0x1400005afd0
        arrow.jpgsp=0x1400005afd0 pc=0x1044ea2a4
created by testing.(*T).Run
        /usr/local/go/src/testing/testing.go:1486 +0x300

goroutine 1 [chan receive]:
testing.tRunner.func1()
        /usr/local/go/src/testing/testing.go:1405 +0x45c
testing.tRunner(0x1400010b1e0, 0x14000131cb8)
        /usr/local/go/src/testing/testing.go:1445 +0x14c
testing.runTests(0x140001421e0?, {0x10466dea0, 0x1, 0x1}, {0xa500000000000000?,
arrow.jpg0x104499218?, 0x104676640?})
        /usr/local/go/src/testing/testing.go:1837 +0x3f0
testing.(*M).Run(0x140001421e0)
        /usr/local/go/src/testing/testing.go:1719 +0x500
main.main()
        _testmain.go:47 +0x1d0

exit status 2
FAIL    demo    0.260s

Go Version: go1.19

Wrapping Up Read/Write Mutexes

While there are pitfalls and areas of concern when using mutexes, such as deadlocks and improper usage, sync.Mutex and sync.RWMutex are excellent tools for protecting shared resources. They are also the most commonly used locking mechanisms in Go.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020