go - exit program when all goroutines finish -


i have 2 go routine functions, 1 creates data , 1 adds data database. when i'm done creating data want finish adding data don't know how many times i'm going call function.

for {   select {   case c <- datachan:     go func() {       if data == false {         return // keeps program running never exits       }       createdata(c.data) // sends data datachan until data == false      }     go func() {       adddata(c.data) // need keep program running until these goroutines finish     }   } } 

createdata() creates , sends data datachan , based on variables set data false , cause program held open returning on , on again , stops creating more data, feel there should cleaner way allows me exit when adddata() goroutines finish. have seen people use channel don't know how many times i'm going call function.

update: working code

var wg sync.waitgroup {   select {   case c <- datachan:     wg.add(1)     go func() {       if data == false {         wg.wait()         os.exit(0)       }       createdata(c.data)     }     go func() {       adddata(c.data)       defer wg.done()     }   } } 

sync.waitgroup want here. wg.add(1) before starting each goroutine (or wg.add(n) if know count front), wg.done() in each routine when finished, , wg.wait() in main wait untill finish. linked docs have example, , docs note, copying won't want; may want make variable pointer (wg := new(sync.waitgroup)).


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -