Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion remoting/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package remoting

import (
"bytes"
"sync"
)

// Codec is the interface that wrap EncodeRequest、 EncodeResponse and Decode method
Expand All @@ -34,12 +35,19 @@ type DecodeResult struct {
Result any
}

var codec = make(map[string]Codec, 2)
var (
codecMu sync.RWMutex
codec = make(map[string]Codec, 2)
)

func RegistryCodec(protocol string, codecTmp Codec) {
codecMu.Lock()
defer codecMu.Unlock()
codec[protocol] = codecTmp
}

func GetCodec(protocol string) Codec {
codecMu.RLock()
defer codecMu.RUnlock()
return codec[protocol]
}
26 changes: 26 additions & 0 deletions remoting/codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package remoting

import (
"bytes"
"sync"
"testing"
)

Expand Down Expand Up @@ -101,3 +102,28 @@ func TestCodecInterface(t *testing.T) {
assert.NotNil(t, result)
assert.Equal(t, 9, length)
}

func TestConcurrentCodecAccess(t *testing.T) {
const goroutines = 100
var wg sync.WaitGroup
wg.Add(goroutines * 2)

// Concurrent writers
for i := 0; i < goroutines; i++ {
go func(i int) {
defer wg.Done()
RegistryCodec("concurrent-"+string(rune('a'+i%26)), &mockCodec{})
}(i)
}

// Concurrent readers
for i := 0; i < goroutines; i++ {
go func(i int) {
defer wg.Done()
GetCodec("concurrent-" + string(rune('a'+i%26)))
}(i)
}

wg.Wait()
// If we reach here without a panic, the concurrent access is safe.
}
Comment on lines +106 to +129
Loading