I'm currently trying to range
over a map
to do concurrent database requests rather than synchronously, obviously because of the speed boost.
My problem is I have something like this:
var mainthreads = make(chan *mainthread)
var mainthreadsFetched = make(chan struct{})
for containerid := range containers {
go func() {
rows, err := db.Query("SELECT thread_id, belongs_to, thread_name, access_level FROM forum_mainthread WHERE belongs_to = ?", containerid)
defer rows.Close()
if err != nil {
log.Println(err)
}
for rows.Next() {
mainthread := &MainThread{}
err := rows.Scan(&mainthread.MainThreadID, &mainthread.BelongsTo, &mainthread.ThreadName, &mainthread.AccessLevel)
if err != nil {
log.Println(err)
}
mainthreads <- mainthread
}
}()
mainthreadsFetched <- struct{}{}
}
// Get all mainthreads
<-mainthreadsFetched
// Do other stuff after complete
Obviously mainthreadsFetched <- struct{}{}
is being called almost instantly because the loop finishes faster than you can blink, how can I create a new channel per loop that will not block each new goroutine
from starting, but rather let the loop start all goroutines
and then send out on a channel when every goroutine
is done.