-2

I read this post about data races. And I understand, that access to interface variable need to be sync. But what about access to struct?

For example we have this code:

package main

import (
    "fmt"
)

type s struct {
    field0 uint8
    field1 uint16
}

func main() {
    s0 := s{
        field0: 1,
        field1: 2,
    }
    s1 := s{
        field0: 3,
        field1: 4,
    }

    var shared s
    var loop0, loop1 func()

    loop0 = func() {
        shared = s0
        go loop1()
    }

    loop1 = func() {
        shared = s1
        go loop0()
    }

    go loop0()

    for {
        fmt.Println(shared)
    }
}

I build this code with -race flag and race detector no detect any errors. But if shared is not a pointer, what really happened? We need set 2 fields (if on stack).

Questions:

  1. is it data race?
  2. if no, why?

UPD: start loop0

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • 1
    There's no data race because while you've defined `loop0` and `loop1`, *you never call them*. There is nothing running concurrently in your code, therefore no possibility of a race. – Adrian Sep 11 '19 at 14:25

1 Answers1

0
  1. is it data race?

Yes. Your loop1 and loop2 won't race with each other, but they both will race with your for { fmt.Println() } loop, because fmt.Println reads at the same time the other functions are writing to the same value.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • If you run it enough times, the race detector probably will catch it. loop0 and loop1 won't race with each other because they never set the value simultaneously. – Jonathan Hall Sep 11 '19 at 14:39