4 ms·
The multi-core Go benchmark is spawning the goroutines before calling `start := time.Now()`.
by mappu 9y ago
The multi-core Go benchmark is spawning the goroutines before calling `start := time.Now()`.
- rollcat 9y agoGo's concurrency model defines that memory writes in one goroutine won't be observable in another until a context switch can happen (e.g. by send/recv on a channel). In practice, newly spawned goroutines often don't get the chance to run at all until that context switch. But yeah, it's not a good idea to rely on this behavior here.
- zlynx 9y agoI'm not sure where you got that information? Go's goroutines launch on threads when multiple CPUs are available. They have all the race conditions of C code. Memory writes certainly are visible on other goroutines.
- rollcat 9y ago> I'm not sure where you got that information? From the very official spec? https://golang.org/ref/mem https://golang.org/ref/mem Goroutines do not map to OS threads 1:1. Whether the scheduler decides to spawn a thread or not is its own, entirely private decision. No action is guaranteed to be taken until scheduling occurs.
- zlynx 8y agoWell, from that spec: "When multiple goroutines access a shared variable v, they must use synchronization events to establish happens-before conditions that ensure reads observe the desired writes." However, that very specifically does NOT say that writes may not be observed BEFORE synchronization events. They MAY. Under "Incorrect Synchronization": "Note that a read r may observe the value written by a write w that happens concurrently with r. Even if this occurs, it does not imply that reads happening after r will observe writes that happened before w." These memory ordering rules are the same as C, C++ or machine code. Go makes no special effort to avoid the natural machine behavior of x86, ARM or MIPS. And on goroutine spawning and execution order, I have observed both behaviors. Sometimes Go will continue on the current goroutine before launching other goroutines. Other times the new goroutines begin executing immediately. It's possible that some other, background goroutine is causing a scheduling event, but if so it's so random that no one could predict it.