Home > Backend Development > Golang > Why Is My Goroutine\'s Value Not Visible to Others?

Why Is My Goroutine\'s Value Not Visible to Others?

Linda Hamilton
Release: 2024-10-29 11:37:30
Original
733 people have browsed it

Why Is My Goroutine's Value Not Visible to Others?

Is this because the go compiler optimized the code?

The issue is not an optimization by the Go compiler, but rather a lack of synchronization. The assignment to i is not followed by any synchronization event, so it is not guaranteed to be observed by any other goroutine. In fact, an aggressive compiler might delete the entire i statement.

The Go Memory Model

The Go memory model specifies the conditions under which reads of a variable in one goroutine can be guaranteed to observe values produced by writes to the same variable in a different goroutine.

To serialize access, protect the data with channel operations or other synchronization primitives such as those in the sync and sync/atomic packages.

If you must read the rest of this document to understand the behavior of your program, you are being too clever. Don't be clever.

Synchronization

In the following example, the assignment to a is not followed by any synchronization event, so it is not guaranteed to be observed by any other goroutine. In fact, an aggressive compiler might delete the entire go statement.

<code class="go">var a string

func hello() {
  go func() { a = "hello" }()
  print(a)
}</code>
Copy after login

The following example shows how to serialize access to i using a sync.Mutex.

<code class="go">package main

import (
    "sync"
    "time"
)

func main() {
    mx := new(sync.Mutex)
    i := 1
    go func() {
        for {
            mx.Lock()
            i++
            mx.Unlock()
        }
    }()
    <-time.After(1 * time.Second)
    mx.Lock()
    println(i)
    mx.Unlock()
}</code>
Copy after login

The above is the detailed content of Why Is My Goroutine\'s Value Not Visible to Others?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template