Why for loop in a G take no effect on i++?

package main

import (

func main() {
	var x int
	go func() {
		for {
	fmt.Println("x =", x) // x = 0, why?

thanks :slight_smile:

Because your goroutine never had the opportunity to run. main exits before the scheduler schedules it. You need some sort of synchronization like a channel or sync.WaitGroup

Shouldn’t time.Sleep() give other go routines the opportunity to run?

I found some explanation here

If it is just for counting you can use atomic counters

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.