Calculation is in sequence instead of concurrent

https://play.golang.org/p/yMvf6pPEo0C

I am new to golang trying to understand concurrency pattern in golang
I am trying to calculate square of set of numbers concurrently but every time it’s calculating in sequential manner. i.e from 0 to 25 in sequence. Am I doing something wrong ?
Any help would be appreciated. Thanks in advance.

The calculation is so fast that the order of items is kept. Try to sleep between reading from jobs and writing to results:

	for n := range jobs {
		time.Sleep(10 * time.Millisecond)
		results <- square(n)
	}

This way the order changes:

$ ./square
1
4
0
25
9
16
49
64
...

see https://play.golang.org/p/P7ek45wtR0-

1 Like

Thanks for replying. Can you please explain why sleeping between reads or writes changes the order?

The execution is so fast that one worker does all the calculations and the others have not even started yet. The sleeping gives a chance to the other workers to do their job.

1 Like

Now I understood. Thanks for replying.

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