Print alphabet concurrently

Hi, I need help with a task: The Go Playground

In the func pool() I create a pool and fill it with IDs (int values).
After that I initialized two functions:

  • worker: get id from pool and concurrently run the func which prints the letters. in the end I return the id to the pool
  • waitDone: waits for all ids to return

And I’m stuck with solving the task. I need to print all the letters concurrently without using time.Sleep and sync package

Hi @daddarrrio, welcome to the forum.

I looked at the code, and it looks a bit convoluted given that the task sounds quite simple—to print letters from a slice of strings.

What do you mean by “print all the letters concurrently”?
What is the exact expected output?
What is the point of making this code concurrent?
Why do you need a pool and workers?
And what exactly are you stuck on?

1 Like

@christophberger I need to print the alphabet using a lot of goroutines. In the example there are two workers == two goroutines, but the code should work for 4, 10 or 1000 goroutines, and the text itself that we print may be larger.

The exact output may differ due to goroutines, but it should eventually print the entire text.

What is the point of making this code concurrent?
Why do you need a pool and workers?

because it’s my task =)

And what exactly are you stuck on?

I get a deadlock in the pool function

Deadlocks often happen when one goroutine cannot write into a channel because the other goroutine is not ready for reading.

What you could do:

  • Put log.Println() statements in every place where something interesting happens, e.g. when sending something into a channel, when a function starts or ends, etc. Decide which lines are interesting enough to place a Println statement before or after that line.
  • Then see what the program prints until it deadlocks.

The output can help narrow down the reason for the deadlock.

1 Like

When I run your code in the playground, I don’t get a deadlock, it just exits without printing anything. I believe this is because your worker function starts f in a goroutine but then immediately returns i to the pool so that your waitDone goroutine started from main later is able to retrieve everything from the pool and exits before the f goroutines start:

worker := func(l string) {
	i := <-pool
	go f(i, l)
	pool <- i

I think you want to only return i to the pool after f completes.

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