在runtime中有 和 两个函数,这两个函数有什么作用呢?我们看一下标准库中对它们的解释。

runtime.LockOSThread

// LockOSThread wires the calling goroutine to its current operating system thread.
// The calling goroutine will always execute in that thread,
// and no other goroutine will execute in it,
// until the calling goroutine has made as many calls to
// UnlockOSThread as to LockOSThread.
// If the calling goroutine exits without unlocking the thread,
// the thread will be terminated.
//
// All init functions are run on the startup thread. Calling LockOSThread
// from an init function will cause the main function to be invoked on
// that thread.
//
// A goroutine should call LockOSThread before calling OS services or
// non-Go library functions that depend on per-thread state.
LockOSThread绑定goroutine线程goroutinegoroutineUnlockOSThreadLockOSThread独占
UnlockOSThread

我们知道在golang中创建的线程正常情况下是无法被销毁的,但通过这种hack用法则可以将其销毁,参考《极端情况下收缩 Go 的线程数》。

init函数init函数LockOSThreadmain
OS服非Go库函数LockOSThread

总结

LockOSThread独占系统线程goroutine的调度机制UnlockOSThread
UnlockOSThread

嵌套调用

LockOSThreadUnlockOSThredgoroutineLockOSThreadgoroutineLockOSThread

runtime.UnlockOSThread

// UnlockOSThread undoes an earlier call to LockOSThread.
// If this drops the number of active LockOSThread calls on the
// calling goroutine to zero, it unwires the calling goroutine from
// its fixed operating system thread.
// If there are no active LockOSThread calls, this is a no-op.
//
// Before calling UnlockOSThread, the caller must ensure that the OS
// thread is suitable for running other goroutines. If the caller made
// any permanent changes to the state of the thread that would affect
// other goroutines, it should not call this function and thus leave
// the goroutine locked to the OS thread until the goroutine (and
// hence the thread) exits.
UnlockOSThreadLockOSThread
goroutineLockOSThreadgoroutineLockOSThreadUnlockOSThread
LockOSThread
UnlockOSThread

总结

UnlockOSThreadLockOSThreadLockOSThread有可能UnlockOSThread

参考资料