Mar 6, 2020

[Go] cgo function call act as a system blocking call for Go's scheduler point of view

email thread:
https://groups.google.com/forum/#!msg/golang-nuts/QydReNgFe00/CsMsWKdzAwAJ

Current fact(GO 1.14):
the Go scheduler will actively try to interrupt CGO calls that take too long.


Quote from Ian Lance Taylor:
When a cgo call starts it has a P attached to it (in the scheduler, a P is a virtual processor; there are exactly GOMAXPROCS P's at all times).

If the cgo call completes quickly, it will simply carry on with the same P.

When the system monitoring thread wakes up, it will check each P to see if it has been waiting for a cgo call to complete for more than a scheduler tick (20 microseconds, more or less).

If so, the P will be stolen and some other M (operating system thread) will be woken up to start using the P and running Go code. (added: since C/C++ code is considered in blocking state)

When the cgo call completes, the goroutine will see that it no longer has a P, and will go to sleep waiting for a P to become available (more or less as though the goroutine called runtime.Gosched).

So in that sense, cgo calls will be interrupted: the P will be removed and reassigned to do other work. However, the actual C/C++ code running on the M (operating system thread) will not be affected.  And the G (goroutine) will of course remain asleep waiting for the cgo call to complete. (This is all a description of the current 1.14 scheduler, and it may be different in other releases.)


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.