#How do I make my code concurrent as I want

27 messages · Page 1 of 1 (latest)

dusk mortar
#

I am learning concurrency and I want the following code to output

print in worker function
print in inner anonymous function
Done

Here is the code

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup
    wg.Add(2)
    go func() {
        defer wg.Done()
        go worker()
        go func() {
            defer wg.Done()
            fmt.Println("print in inner anonymous function")
        }()
    }()
    wg.Wait()
    fmt.Println("Done")
    time.Sleep(time.Second)
}

func worker() {
    fmt.Println("print in worker function")
}
grand jetty
#

The way you have set up now, there’s no guarantee that worker() will run before the inner anonymous function print will

dusk mortar
#

How should I set it up then

wispy pawn
sudden raven
#

^ lol

grand jetty
#

You don’t need that worker goroutine

wispy pawn
#

@dusk mortar if you want code to excute sequentially then you don't want concurrency

dusk mortar
#

What is the use of waitgroup then?

#

isn't it to wait for goroutines?

sudden raven
#

when u wanna wait for some functions to finish and then continue ur sequential code

wispy pawn
#

but it doesn't do anything for the two workers

dusk mortar
#

so I shouldn't use concurrency because I want it to be in sequency?

#

Ok

#

more like I wanted to understand how waitgroup work so I am experimenting things out

#

where can I understand waitgroup from?

#

Any recommended book/guide/document?

queen tendon
#

waitgroup means, i have 10 workers, i want to wait until they all stopped

wispy pawn
# dusk mortar where can I understand waitgroup from?

You are just using it for something that don't need it.

Try doing something else, for example try to download multiple URLs at once.
Create a program that accepts a list of URLs and download all of them in parallel.
It will become obvious what waitgroup do

dusk mortar
#

oh ok

#

I will try

#

Thanks guys

queen tendon
dusk mortar
#

I will try

#

understanding concurrency in general will take a lot of time

wispy pawn
queen tendon
#

that's assuming you want it sorted by alphanumeric for arbitrary reasons
but otherwise you could just directly for range the channel and display results as soon as they are done