Keep getting fatal error: all goroutines are asleep - deadlock!

Hey! I’m trying to make a code for a lot of data ant want to use concurrancy.

It needs to print the lines in the same order, but words should be in the correct order(that works fine)

However, I keep getting “fatal error: all goroutines are asleep - deadlock!” and my lines are not in the same order.

Here is my code: https://play.golang.org/p/mw3B4Tqqs7S

Hello,

You must wait for wg in main thread, you don’t need a goroutine for it. You should range over results in a goroutine not to block main thread.

Your main goroutine is looping through the results channel and the goroutine that closes it doesn’t get started until after the loop. The loop will call writeToFile on all the results but will then wait for more results in the channel that will never happen.

I recommend adding a separate goroutine responsible for writing the results out to the file and use a second wait group for it. The process essentially becomes:

  • Create the consumer waitgroup and goroutine
  • Create your worker waitgroup and goroutines. As they complete, make sure to call Done.
  • Call Wait on your worker waitgroup. It’ll return after the last worker completes. Close the results channel and then wait on your consumer’s wait group to finish.

Example: https://play.golang.org/p/FsnVlJl5j4U

Hi Skillian,

You code does solve the deadlock issue, but the ordering still have issues. I have made few changes which helps preserve the line order.

  • After scanning each line and sorting, I have written the line to the result and add a wait for each goroutine instead of waiting for all go routines at one.

refer the code at https://play.golang.org/p/6Tqfd8kawX2

refer the requested fix at “refer the code at Go Playground - The Go Programming Language” and let me know is this what you have expected

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