Advertisement
Falexom

Untitled

Apr 26th, 2024
707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.52 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "sync/atomic"
  5. )
  6.  
  7. type WaitGroup interface {
  8.     Add(delta int)
  9.     Done()
  10.     Wait()
  11. }
  12.  
  13. type WG struct {
  14.     count int32
  15. }
  16.  
  17. func NewWaitGroup() *WG {
  18.     return &WG{
  19.         count: 0,
  20.     }
  21. }
  22.  
  23. func (wg *WG) Add(delta int) {
  24.     atomic.AddInt32(&wg.count, int32(delta))
  25. }
  26.  
  27. func (wg *WG) Done() {
  28.     if atomic.LoadInt32(&wg.count) > 0 {
  29.         atomic.AddInt32(&wg.count, -1)
  30.     } else {
  31.         panic("negative counter")
  32.     }
  33. }
  34.  
  35. func (wg *WG) Wait() {
  36.     for {
  37.         if atomic.LoadInt32(&wg.count) == 0 {
  38.             break
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement