Last active
May 9, 2019 21:49
-
-
Save bschaeffer/9c54e799dc455bb25fba5e17e0740807 to your computer and use it in GitHub Desktop.
Shared Request - Shares a single request across multiple go routines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
type SharedRequest struct { | |
data string | |
loading bool | |
lock sync.Mutex | |
wg sync.WaitGroup | |
} | |
func (r *SharedRequest) Exec() { | |
r.lock.Lock() | |
defer r.lock.Unlock() | |
if !r.loading { | |
r.loading = true | |
r.wg.Add(1) | |
go func() { | |
time.Sleep(5 * time.Second) | |
r.wg.Done() | |
}() | |
} | |
} | |
func (r *SharedRequest) Wait() { | |
r.wg.Wait() | |
} | |
func main() { | |
req := &SharedRequest{} | |
req.Wait() | |
fmt.Println("Done") | |
start := time.Now() | |
for i := 0; i < 4; i++ { | |
req.Exec() | |
} | |
time.Sleep(2 * time.Second) | |
for i := 0; i < 4; i++ { | |
req.Exec() | |
} | |
req.Wait() | |
duration := time.Since(start) | |
fmt.Println("Done", duration) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment