Skip to content

Commit 0be1ffb

Browse files
l2dyedsiper
authored andcommitted
output: make plugin context operations safe for concurrent use
Signed-off-by: Zero King <[email protected]>
1 parent 7785f07 commit 0be1ffb

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

output/output.go

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ package output
2424
*/
2525
import "C"
2626
import (
27+
"sync"
2728
"unsafe"
2829
)
2930

@@ -69,22 +70,24 @@ func FLBPluginConfigKey(plugin unsafe.Pointer, key string) string {
6970
return value
7071
}
7172

72-
var contexts = make(map[uintptr]interface{})
73+
var contexts sync.Map
7374

75+
// FLBPluginSetContext sets the context for plugin to ctx.
76+
//
77+
// Limit FLBPluginSetContext calls to once per plugin instance for best performance.
7478
func FLBPluginSetContext(plugin unsafe.Pointer, ctx interface{}) {
7579
// Allocate a byte of memory in the C heap and fill it with '\0',
7680
// then convert its pointer into the C type void*, represented by unsafe.Pointer.
7781
// The C string is not managed by Go GC, so it will not be freed automatically.
7882
i := unsafe.Pointer(C.CString(""))
79-
// uintptr(i) produces the memory address of i, and malloc() guarantees uniqueness of it.
80-
//
81-
// FLBPluginSetContext must not be called concurrently with itself or FLBPluginGetContext.
82-
// A sync.RWMutex must be added if this might happen.
83-
contexts[uintptr(i)] = ctx
83+
// uintptr(i) returns the memory address of i, which is unique in the heap.
84+
contexts.Store(uintptr(i), ctx)
8485
p := (*FLBOutPlugin)(plugin)
8586
p.context.remote_context = i
8687
}
8788

88-
func FLBPluginGetContext(i unsafe.Pointer) interface{} {
89-
return contexts[uintptr(i)]
89+
// FLBPluginGetContext reads the context associated with proxyCtx.
90+
func FLBPluginGetContext(proxyCtx unsafe.Pointer) interface{} {
91+
v, _ := contexts.Load(uintptr(proxyCtx))
92+
return v
9093
}

0 commit comments

Comments
 (0)