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.
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.