Occured incomprehensible deadlock

That, you can start with concurrency planning with crisp and clear data transfers. You can use flow chart or pseudo-code. Here’s one example using pseudo-code:

Process 0 (main):

  1. make channel with 10 buffer space
  2. set my i limit to 100.
  3. start p1 process.
  4. start reading from channel until it closed.
  5. terminate entire program.

Process 1 (let’s name it p1):

  1. loop from 0 to limit, named value
  2. for each value, send value to channel then sleep for 2 seconds
  3. close channel once done.
  4. terminate p1 process.

Keywords:

  1. must be clear with ***WHO does WHAT at WHEN***, every single step for every processes.

You can try it out on your own. I re-coded the example to match the pseudo-code so be self-disciplined over there, all right?

An example answer:

package main

import (
	"fmt"
	"time"
)

func p1(limit int, ch chan int) {
	for value := 0; value < limit; value++ {
		ch <- value
		time.Sleep(time.Second * 2)
	}

	// done with operation, close channel.
	close(ch)
}

func main() {
	ch := make(chan int, 10)
	i := 100

	// start p1 process
	go p1(i, ch)

	// read from channel
	for i := range ch {
		fmt.Println(i)
	}

	fmt.Println("[ END ]")
}
2 Likes