简体   繁体   English

go 通道和 goroutines 是如何翻译成 webassembly 的?

[英]How are go channels and goroutines translated to webassembly?

Have been programming in Go from quite some time, and started looking into WebAssembly lately.很长一段时间以来一直在 Go 编程,最近开始研究 WebAssembly。 While most of the things are straightforward, have a question around translating some of the Go specific constructs like channels and goroutines to wasm.虽然大多数事情都很简单,但对于将一些 Go 特定结构(如通道和 goroutines)转换为 wasm 有疑问。 Do they behave in the same way when used from JS as they would in Go (eg goroutines are exposed as async functions to JS, etc.)?它们在 JS 中使用时的行为方式是否与在 Go 中的行为方式相同(例如,goroutines 作为异步函数暴露给 JS 等)?

The WASM target of the go compiler does not currently support threads, or as Go calls them "procs". go 编译器的 WASM 目标当前不支持线程,或者 Go 将它们称为“procs”。

This means that, from the perspective of a user of the language and simplifying a bit, a Go program running on WASM behaves as a Go program running with GOMAXPROCS=1 on any other platform.这意味着,从语言用户的角度并稍微简化一下,在 WASM 上运行的 Go 程序的行为就像在任何其他平台上以GOMAXPROCS=1运行的 Go 程序一样。

Crucially, as long as you use proper synchronization in your code, nothing should change from a correctness standpoint.至关重要的是,只要您在代码中使用适当的同步,从正确性的角度来看,什么都不会改变。 This includes the semantics of channels and goroutines, in the same way these semantics do not change when you run your code with GOMAXPROCS=1 .这包括通道和 goroutine 的语义,就像当您使用GOMAXPROCS=1运行代码时这些语义不会改变一样。

The way this works is by including the go runtime (and its scheduler) in the built WASM module.其工作方式是在内置的 WASM 模块中包含 go 运行时(及其调度程序)。 The go runtime, exactly like in the case of GOMAXPROCS=1 is able to multiplex execution of multiple goroutines even if only a single thread/proc is available. go 运行时,就像在GOMAXPROCS=1的情况下一样,即使只有一个线程/proc 可用,也能够多路复用多个 goroutine 的执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM