gpt4 book ai didi

go - 如何防止同步池创建两个实例

转载 作者:行者123 更新时间:2023-12-01 22:40:13 26 4
gpt4 key购买 nike

我正在实现一个TCP连接池以记录到流利的比特,这是代码

import (
"fmt"
"log"
"net"
"sync"
)

type FluentConnectionPool struct {
sync.Mutex
pool *sync.Pool
}

func (fl *FluentConnectionPool) Log(message string) {
fl.Lock()
defer fl.Unlock()

conn := fl.pool.Get().(*net.TCPConn)
defer fl.pool.Put(conn)

fmt.Printf("using: %v\n", conn.LocalAddr())

if _, err := conn.Write([]byte(message)) ; err != nil {
log.Fatal(err)
}
}

func (fl *FluentConnectionPool) Close() {
conn := fl.pool.Get().(*net.TCPConn)
defer conn.Close()

fmt.Printf("Closing: %v\n", conn.LocalAddr())
}

func New(address string) (*FluentConnectionPool, error) {
fluentAddress, err := net.ResolveTCPAddr("tcp", address)

if err != nil {
return nil, err
}

pool := &sync.Pool{New: func() interface{} {
connection, _ := net.DialTCP("tcp", nil, fluentAddress)
return connection
}}

return &FluentConnectionPool{
pool: pool,
}, nil
}

当我测试这样的代码时

import "time"

func main() {
pool, _ := New("localhost:5170")
defer pool.Close()

for i := 0 ; i < 10 ; i++ {
go func() {
pool.Log(`{"data": {"name": "name here"}}`)
}()
}

time.Sleep(1 * time.Second)
}

输出是这样的
using: 127.0.0.1:43990
using: 127.0.0.1:43990
using: 127.0.0.1:43990
using: 127.0.0.1:43990
using: 127.0.0.1:43990
using: 127.0.0.1:43990
using: 127.0.0.1:43990
using: 127.0.0.1:43990
using: 127.0.0.1:43990
using: 127.0.0.1:43994
Closing: 127.0.0.1:43994

即使锁定了功能,我也不明白为什么会创建两次连接(43990&43994),所以43990上的连接保持打开状态,您能解释一下为什么会这样吗?

谢谢!

最佳答案

来自Pool文档的这可能解释了行为:

池中存储的任何项目都可以随时自动删除,恕不另行通知。如果发生这种情况时,池中只有唯一的引用,则该项目可能会被释放。

池可能已删除您使用的连接。

关于go - 如何防止同步池创建两个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61597028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com