Native callbacks and thread affinity
Native callbacks and thread affinity
A callback lets native code call an exported Go function. To carry arbitrary Go values through C use runtime/cgo.Handle: a numeric token, not a disguised pointer. Create a handle before passing the token, recover its Value in Go, and Delete only after the native side has stopped using it. The preamble of a file with //export must contain declarations only, because cgo copies it into generated C files. This small synchronous round trip uses a generated C wrapper.
package main
/*#include <stdint.h>extern int goRead(uintptr_t token);*/import "C"import ( "fmt" "runtime/cgo")
//export goReadfunc goRead(token C.uintptr_t) C.int { return C.int(cgo.Handle(token).Value().(int)) }func main() { h := cgo.NewHandle(42); defer h.Delete(); fmt.Println(C.goRead(C.uintptr_t(h))) }The token denotes a Go value in a handle table; it is not a C pointer and must not be dereferenced. The native caller must respect the lifetime. In a real asynchronous registration, unregister and wait for all in-flight callbacks before deleting. Do not allow a panic to escape an exported boundary; design an explicit error/status convention.
Expected output:
42Lock a goroutine to its OS thread
package main
import ( "fmt" "runtime" "syscall")
func main() { runtime.LockOSThread() defer runtime.UnlockOSThread() before := syscall.Gettid() runtime.Gosched() fmt.Println(before == syscall.Gettid())}Some native APIs store state in thread-local storage or require an event loop on a particular thread. LockOSThread binds this goroutine to its current OS thread until matching unlocks. It does not choose a special UI thread, protect other shared state or make callbacks single-threaded. This Gettid probe is Linux-specific; use the native platform contract for actual affinity requirements.
Expected output:
trueTry it locally
Pass two independent integer values through C using two handles, invoke the callback for each and delete both after the final call. Print their sum.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Native interoperability 03: Native callbacks and thread affinity
Check the lesson objective before moving on.
When is it safe to delete a handle used by an asynchronous native callback?
What does LockOSThread guarantee?