Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to lock/synchronize access to a variable in Go during concurrent goroutines?
    primarykey
    data
    text
    <p>In his answer to this question: <a href="https://stackoverflow.com/questions/3918941/golang-for-windows-erratic-behavior">Golang for Windows erratic behavior?</a> user @distributed recommended to lock/synchronize access to a shared variable on concurrent goroutines.</p> <p>How can I do that?</p> <p>More on the issue:</p> <p>I get this code (the returned function with a closure on <code>views</code>) running on several goroutines at the same time:</p> <pre><code>func makeHomeHandler() func(c *http.Conn, r *http.Request) { views := 1 return func(c *http.Conn, r *http.Request) { fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views) views++ } } </code></pre> <p>It looks like the IO function takes it's time, and as a result I get this kind of output:</p> <pre><code>Counting monkeys, 5 so far. Counting monkeys, 5 so far. Counting monkeys, 5 so far. Counting monkeys, 8 so far. Counting monkeys, 8 so far. Counting monkeys, 8 so far. Counting monkeys, 11 so far. </code></pre> <p>It increments fine, but when it gets printed I can see that the operation printing+incrementing is not atomic at all.</p> <p>If I change it to:</p> <pre><code>func makeHomeHandler() func(c *http.Conn, r *http.Request) { views := 0 return func(c *http.Conn, r *http.Request) { views++ // I can only hope that other goroutine does not increment the counter // at this point, i.e., right after the previous line and before the // next one are executed! views_now := views fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views_now) } } </code></pre> <p>It seems to work fine, but I'm not completely sure if it will not fail eventually... </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload