Skip to content

Commit

Permalink
add async method
Browse files Browse the repository at this point in the history
  • Loading branch information
lxzan committed May 22, 2024
1 parent 834d703 commit 943afb7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@ func (c *Conn) WritevAsync(opcode Opcode, payloads [][]byte, callback func(error
})
}

// Async 异步
// 将任务加入发送队列(并发度为1), 执行异步操作
// 注意: 不要加入长时间阻塞的任务
// Add the task to the send queue (concurrency 1), perform asynchronous operation.
// Note: Don't add tasks that are blocking for a long time.
func (c *Conn) Async(f func()) {
c.writeQueue.Push(f)
}

// 执行写入逻辑, 注意妥善维护压缩字典
func (c *Conn) doWrite(opcode Opcode, payload internal.Payload) error {
c.mu.Lock()
Expand Down
20 changes: 20 additions & 0 deletions writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -489,3 +489,23 @@ func TestConn_Writev(t *testing.T) {
assert.Error(t, err)
})
}

func TestConn_Async(t *testing.T) {
var conn = &Conn{writeQueue: workerQueue{maxConcurrency: 1}}
var wg = sync.WaitGroup{}
wg.Add(100)
var arr1, arr2 []int64
var mu = &sync.Mutex{}
for i := 1; i <= 100; i++ {
var x = int64(i)
arr1 = append(arr1, x)
conn.Async(func() {
mu.Lock()
arr2 = append(arr2, x)
mu.Unlock()
wg.Done()
})
}
wg.Wait()
assert.ElementsMatch(t, arr1, arr2)
}

0 comments on commit 943afb7

Please sign in to comment.