On Mon, Jun 11, 2018 at 12:15 AM, <
mizze...@gmail.com> wrote:
>
> I shouldn't have mentioned well-behaved functions. It's a whole other topic.
> I'm interested specifically in goroutine stacks.
> Theoretically, can they be used to run C code?
> Are there any pitfalls?
Yes, theoretically, if you have a large goroutine stack, it could be
used to run C code.
>>For that matter, treating cgo calls specially on one
>>specific goroutine is also likely to have unexpected performance
>>characteristics for people who aren't very careful about how they
>>write their code.
> Yeah, such a solution looks inflexible. But I can think of another.
> What if there were a compiler directive to adjust a Go function's stack
> growing strategy?
> Something like this:
> //go:stack_always_grow=1MB
> func func_with_cgocalls()
>
> That way, when func_with_cgocalls is entered, a calling goroutine's stack is
> always incremented by 1MB. Thus, within the function the cgo transpiler
> could emit more effective Cgo calls avoiding switching to a system stack.
> Naturally, when the function is left, the stack is shrunk back.
>
> P.S. The cost of switching the stacks is around 7 nanoseconds per call (on
> my system).
> //Which alone is comparable to the cost of a JNI call (from Java to C).
> The optimization may be or not be worth it, depending on context.
What are you measuring?
As you've already observed, switching the stacks is only part of a cgo
call. The more expensive part is telling the scheduler that the
thread is entering C code.
Ian