From 307e500b82abb3e48851971346fd866ec96d938d Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Sat, 23 Dec 2023 18:10:57 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E5=A2=9E=E5=8A=A0=20writeloop=20?= =?UTF-8?q?=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/writeloop/README.md | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 server/writeloop/README.md diff --git a/server/writeloop/README.md b/server/writeloop/README.md new file mode 100644 index 0000000..50f6c6f --- /dev/null +++ b/server/writeloop/README.md @@ -0,0 +1,52 @@ +# WriteLoop + +[![Go doc](https://img.shields.io/badge/go.dev-reference-brightgreen?logo=go&logoColor=white&style=flat)](https://pkg.go.dev/github.com/kercylan98/minotaur/server/writeloop) + +该包提供了一个并发安全的写循环实现。开发者可以使用它来快速构建和管理写入操作。 + +## WriteLoop [`写循环`](https://pkg.go.dev/github.com/kercylan98/minotaur/server/writeloop#WriteLoop) + +写循环是一种特殊的循环,它可以并发安全地将数据写入到底层连接。写循环在 `Minotaur` 中是一个泛型类型,可以处理任意类型的消息。 + +> [`WriteLoop`](https://pkg.go.dev/github.com/kercylan98/minotaur/server/writeloop#WriteLoop) 使用了 [`Pool`](https://pkg.go.dev/github.com/kercylan98/minotaur/utils/concurrent#Pool) 和 [`Unbounded`](https://pkg.go.dev/github.com/kercylan98/minotaur/utils/buffer#Unbounded) 进行实现。 +> 通过 [`Pool`](https://pkg.go.dev/github.com/kercylan98/minotaur/utils/concurrent#Pool) 创建的消息对象无需手动释放,它会在写循环处理完消息后自动回收。 + +### 使用示例 + +```go +package main + +import ( + "fmt" + "github.com/kercylan98/minotaur/server/writeloop" + "github.com/kercylan98/minotaur/utils/concurrent" +) + +func main() { + pool := concurrent.NewPool[Message](func() *Message { + return &Message{} + }, func(data *Message) { + data.ID = 0 + }) + var wait sync.WaitGroup + wait.Add(10) + wl := writeloop.NewWriteLoop(pool, func(message *Message) error { + fmt.Println(message.ID) + wait.Done() + return nil + }, func(err any) { + fmt.Println(err) + }) + + for i := 0; i < 10; i++ { + m := pool.Get() + m.ID = i + wl.Put(m) + } + + wait.Wait() + wl.Close() +} +``` + +在这个示例中,我们创建了一个写循环,然后将一些消息放入写循环。每个消息都会被 `writeHandle` 函数处理,如果在处理过程中发生错误,`errorHandle` 函数会被调用。在使用完写循环后,我们需要关闭它。 \ No newline at end of file