Skip to content

Commit

Permalink
feat(coroutine): Optimize Wait (#86)
Browse files Browse the repository at this point in the history
* feat(coroutine): Optimize `Wait`

Signed-off-by: Flc゛ <[email protected]>

* feat(coroutine): Optimize `Wait`

Signed-off-by: Flc゛ <[email protected]>

* feat(coroutine): Optimize `Wait`

Signed-off-by: Flc゛ <[email protected]>

---------

Signed-off-by: Flc゛ <[email protected]>
  • Loading branch information
flc1125 authored Jan 31, 2024
1 parent 4c8992a commit f95070f
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 12 deletions.
3 changes: 3 additions & 0 deletions coroutine/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,8 @@ func main() {

// Parallel Example2
coroutine.RunParallel(funcs...)

// Wait Example
coroutine.Wait(funcs...)
}
```
1 change: 0 additions & 1 deletion coroutine/concurrent.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ type Concurrent struct {

func NewConcurrent(limit int) *Concurrent {
return &Concurrent{
wg: sync.WaitGroup{},
ch: make(chan struct{}, limit),
fs: make([]func(), 0),
}
Expand Down
1 change: 0 additions & 1 deletion coroutine/parallel.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ type Parallel struct {

func NewParallel() *Parallel {
return &Parallel{
wg: sync.WaitGroup{},
fs: make([]func(), 0),
}
}
Expand Down
14 changes: 8 additions & 6 deletions coroutine/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package coroutine

import "sync"

func Wait(fn func()) {
func Wait(fs ...func()) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
fn()
wg.Done()
}()
wg.Add(len(fs))
for _, f := range fs {
go func(f func()) {
defer wg.Done()
f()
}(f)
}
wg.Wait()
}
20 changes: 16 additions & 4 deletions coroutine/wait_test.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
package coroutine

import (
"bytes"
"sync"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestWait(t *testing.T) {
var msg string
var (
buffer bytes.Buffer
mu sync.Mutex
)

Wait(func() {
time.Sleep(time.Second)
msg = "hello"
time.Sleep(100 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
buffer.WriteString("hello")
}, func() {
time.Sleep(200 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
buffer.WriteString(" world")
})

assert.Equal(t, "hello", msg)
assert.Equal(t, "hello world", buffer.String())
}

0 comments on commit f95070f

Please sign in to comment.