这是一个深思熟虑的设计决定,还是我们当前浏览器的一个问题,这个问题将在未来的版本中得到纠正?
当前回答
Node.js 10.5+支持工作线程作为实验特性(你可以使用——experimental-worker flag enabled): https://nodejs.org/api/worker_threads.html
所以,规则是:
如果你需要做I/O绑定操作,那么使用内部机制(即callback/promise/async-await) 如果你需要做CPU绑定的操作,那么使用工作线程。
工作线程是长期存在的线程,这意味着生成一个后台线程,然后通过消息传递与它通信。
否则,如果需要使用匿名函数执行较重的CPU负载,则可以使用https://github.com/wilk/microjob,这是一个围绕工作线程构建的小型库。
其他回答
实际上多线程与语言本身没有关系。 这是一个。net的多线程Javascript引擎。 它在多线程场景下工作得非常好。 它集成了c#运行时,所以所有的同步逻辑都类似于c#。可以启动/等待/等待任务,也可以启动线程。你甚至可以放锁。下面的示例演示了在。net运行时中使用Javascript语法的并行循环。
https://github.com/koculu/topaz
var engine = new TopazEngine();
engine.AddType(typeof(Console), "Console");
topazEngine.AddType(typeof(Parallel), "Parallel");
engine.ExecuteScript(@"
var sharedVariable = 0
function f1(i) {
sharedVariable = i
}
Parallel.For(0, 100000 , f1)
Console.WriteLine(`Final value: {sharedVariable}`);
");
除此之外,微软正在开发Napa.js,一个支持多线程的Node.js克隆。
https://github.com/microsoft/napajs
传统上,JS是为简短、快速运行的代码而设计的。如果你需要进行重要的计算,你就需要在服务器上进行——让一个JS+HTML应用程序长时间运行在你的浏览器中做一些重要的事情是荒谬的。
Of course, now we have that. But, it'll take a bit for browsers to catch up - most of them have been designed around a single-threaded model, and changing that is not easy. Google Gears side-steps a lot of potential problems by requiring that background execution is isolated - no changing the DOM (since that's not thread-safe), no accessing objects created by the main thread (ditto). While restrictive, this will likely be the most practical design for the near future, both because it simplifies the design of the browser, and because it reduces the risk involved in allowing inexperienced JS coders mess around with threads...
@marcio:
为什么不使用Javascript实现多线程呢?程序员可以用他们拥有的工具做任何他们想做的事情。
So then, let's not give them tools that are so easy to misuse that every other website i open ends up crashing my browser. A naive implementation of this would bring you straight into the territory that caused MS so many headaches during IE7 development: add-on authors played fast and loose with the threading model, resulting in hidden bugs that became evident when object lifecycles changed on the primary thread. BAD. If you're writing multi-threaded ActiveX add-ons for IE, i guess it comes with the territory; doesn't mean it needs to go any further than that.
目前一些浏览器确实支持多线程。如果你需要,你可以使用特定的库。例如,查看下面的材料:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers (支持后台线程); https://keithwhor.github.io/multithread.js/(图书馆)。
javascript多线程显然是可能的使用HTML5带来的网络工作者。
webworker和标准多线程环境之间的主要区别是内存资源不与主线程共享,对象的引用从一个线程到另一个线程是不可见的。线程通过交换消息进行通信,因此可以实现遵循事件驱动设计模式的同步和并发方法调用算法。
有很多框架允许在线程之间结构化编程,其中包括OODK-JS,这是一个支持并发编程的OOP js框架 https://github.com/GOMServices/oodk-js-oop-for-js
JavaScript多线程(有一些限制)在这里。谷歌实现了Gears的worker, HTML5也包含了worker。大多数浏览器已经添加了对该特性的支持。
数据的线程安全得到了保证,因为所有与worker通信的数据都被序列化/复制。
欲了解更多信息,请阅读:
http://www.whatwg.org/specs/web-workers/current-work/
http://ejohn.org/blog/web-workers/