JavaScript でマルチスレッドを行う方法はありますか?
14 に答える
最新のサポート情報については、http://caniuse.com/#search=workerを参照してください。
以下は2009年頃のサポート状況です。
あなたがググりたい言葉はJavaScript Worker Threadsです
Gearsを除いて、現在利用できるものはありませんが、これを実装する方法についてはたくさんの話があるので、答えが将来変わることは間違いないので、この質問を見てください.
Here's the relevant documentation for Gears: WorkerPool API
WHATWG has a Draft Recommendation for worker threads: Web Workers
And there's also Mozilla’s DOM Worker Threads
Update: June 2009, current state of browser support for JavaScript threads
Firefox 3.5 has web workers. Some demos of web workers, if you want to see them in action:
- Simulated Annealing ("Try it" link)
- Space Invaders (link at end of post)
- MoonBat JavaScript Benchmark (first link)
The Gears plugin can also be installed in Firefox.
Safari 4, and the WebKit nightlies have worker threads:
Chromeには Gears が組み込まれているため、スレッドを実行できますが、ユーザーからの確認プロンプトが必要です (また、Web ワーカーに対して別の API を使用しますが、Gears プラグインがインストールされている任意のブラウザーで動作します)。
- Google Gears WorkerPool Demo (Chrome と Firefox でテストするには実行速度が速すぎるため、良い例ではありませんが、IE では実行速度が遅いため、相互作用がブロックされていることがわかります)
IE8およびIE9は、Gears プラグインがインストールされている場合にのみスレッドを実行できます
JavaScript でマルチスレッドと非同期を行う別の方法
HTML5 より前の JavaScript では、ページごとに 1 つのスレッドしか実行できませんでした。
Yield、setTimeout()
、setInterval()
、XMLHttpRequest
またはイベント ハンドラーを使用して非同期実行をシミュレートするハックな方法がありました( yieldおよびの例については、この投稿の最後を参照してくださいsetTimeout()
)。
しかし HTML5 では、ワーカー スレッドを使用して関数の実行を並列化できるようになりました。使用例はこちら。
真のマルチスレッド
マルチスレッド: JavaScript ワーカー スレッド
HTML5は Web ワーカー スレッドを導入しました (参照:ブラウザの互換性)
注: IE9 以前のバージョンではサポートされていません。
これらのワーカー スレッドは、ページのパフォーマンスに影響を与えずにバックグラウンドで実行される JavaScript スレッドです。Web Worker の詳細については、ドキュメントまたはこのチュートリアルをお読みください。
以下は、MAX_VALUE までカウントされ、現在の計算値をページに表示する 3 つの Web ワーカー スレッドを使用した簡単な例です。
//As a worker normally take another JavaScript file to execute we convert the function in an URL: http://stackoverflow.com/a/16799132/2576706
function getScriptPath(foo){ return window.URL.createObjectURL(new Blob([foo.toString().match(/^\s*function\s*\(\s*\)\s*\{(([\s\S](?!\}$))*[\s\S])/)[1]],{type:'text/javascript'})); }
var MAX_VALUE = 10000;
/*
* Here are the workers
*/
//Worker 1
var worker1 = new Worker(getScriptPath(function(){
self.addEventListener('message', function(e) {
var value = 0;
while(value <= e.data){
self.postMessage(value);
value++;
}
}, false);
}));
//We add a listener to the worker to get the response and show it in the page
worker1.addEventListener('message', function(e) {
document.getElementById("result1").innerHTML = e.data;
}, false);
//Worker 2
var worker2 = new Worker(getScriptPath(function(){
self.addEventListener('message', function(e) {
var value = 0;
while(value <= e.data){
self.postMessage(value);
value++;
}
}, false);
}));
worker2.addEventListener('message', function(e) {
document.getElementById("result2").innerHTML = e.data;
}, false);
//Worker 3
var worker3 = new Worker(getScriptPath(function(){
self.addEventListener('message', function(e) {
var value = 0;
while(value <= e.data){
self.postMessage(value);
value++;
}
}, false);
}));
worker3.addEventListener('message', function(e) {
document.getElementById("result3").innerHTML = e.data;
}, false);
// Start and send data to our worker.
worker1.postMessage(MAX_VALUE);
worker2.postMessage(MAX_VALUE);
worker3.postMessage(MAX_VALUE);
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
3 つのスレッドが同時に実行され、現在の値がページに出力されていることがわかります。これらは分離されたスレッドを使用してバックグラウンドで実行されるため、ページがフリーズすることはありません。
マルチスレッド: 複数の iframe を使用
これを実現する別の方法は、複数のiframeを使用することです。それぞれがスレッドを実行します。URL によってiframeにいくつかのパラメーターを与えることができ、iframeは親と通信して結果を取得し、それを出力することができます ( iframeは同じドメインにある必要があります)。
この例はすべてのブラウザーで機能するわけではありません! iframeは通常、メイン ページと同じスレッド/プロセスで実行されます (ただし、Firefox と Chromium では処理が異なるようです)。
コード スニペットは複数の HTML ファイルをサポートしていないため、ここではさまざまなコードのみを提供します。
index.html:
//The 3 iframes containing the code (take the thread id in param)
<iframe id="threadFrame1" src="thread.html?id=1"></iframe>
<iframe id="threadFrame2" src="thread.html?id=2"></iframe>
<iframe id="threadFrame3" src="thread.html?id=3"></iframe>
//Divs that shows the result
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
<script>
//This function is called by each iframe
function threadResult(threadId, result) {
document.getElementById("result" + threadId).innerHTML = result;
}
</script>
スレッド.html:
//Get the parameters in the URL: http://stackoverflow.com/a/1099670/2576706
function getQueryParams(paramName) {
var qs = document.location.search.split('+').join(' ');
var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params[paramName];
}
//The thread code (get the id from the URL, we can pass other parameters as needed)
var MAX_VALUE = 100000;
(function thread() {
var threadId = getQueryParams('id');
for(var i=0; i<MAX_VALUE; i++){
parent.threadResult(threadId, i);
}
})();
マルチスレッドをシミュレートする
シングルスレッド: setTimeout() で JavaScript の同時実行性をエミュレートする
「素朴な」方法は、次のように関数をsetTimeout()
次々に実行することです。
setTimeout(function(){ /* Some tasks */ }, 0);
setTimeout(function(){ /* Some tasks */ }, 0);
[...]
ただし、各タスクが次々に実行されるため 、この方法は機能しません。
次のように関数を再帰的に呼び出すことで、非同期実行をシミュレートできます。
var MAX_VALUE = 10000;
function thread1(value, maxValue){
var me = this;
document.getElementById("result1").innerHTML = value;
value++;
//Continue execution
if(value<=maxValue)
setTimeout(function () { me.thread1(value, maxValue); }, 0);
}
function thread2(value, maxValue){
var me = this;
document.getElementById("result2").innerHTML = value;
value++;
if(value<=maxValue)
setTimeout(function () { me.thread2(value, maxValue); }, 0);
}
function thread3(value, maxValue){
var me = this;
document.getElementById("result3").innerHTML = value;
value++;
if(value<=maxValue)
setTimeout(function () { me.thread3(value, maxValue); }, 0);
}
thread1(0, MAX_VALUE);
thread2(0, MAX_VALUE);
thread3(0, MAX_VALUE);
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
ご覧のとおり、この 2 番目の方法は非常に遅く、関数の実行にメイン スレッドを使用するため、ブラウザがフリーズします。
シングルスレッド: JavaScript の同時実行性を yield でエミュレートする
YieldはECMAScript 6の新機能で、最も古いバージョンの Firefox と Chrome でのみ機能します (Chrome では、 chrome://flags/#enable-javascript-harmonyに表示される実験的 JavaScriptを有効にする必要があります)。
yield キーワードにより、ジェネレーター関数の実行が一時停止し、yield キーワードに続く式の値がジェネレーターの呼び出し元に返されます。これは、return キーワードのジェネレーター ベースのバージョンと考えることができます。
ジェネレーターを使用すると、関数の実行を一時停止し、後で再開できます。ジェネレーターを使用して、トランポリンと呼ばれる手法で関数をスケジュールできます。
次に例を示します。
var MAX_VALUE = 10000;
Scheduler = {
_tasks: [],
add: function(func){
this._tasks.push(func);
},
start: function(){
var tasks = this._tasks;
var length = tasks.length;
while(length>0){
for(var i=0; i<length; i++){
var res = tasks[i].next();
if(res.done){
tasks.splice(i, 1);
length--;
i--;
}
}
}
}
}
function* updateUI(threadID, maxValue) {
var value = 0;
while(value<=maxValue){
yield document.getElementById("result" + threadID).innerHTML = value;
value++;
}
}
Scheduler.add(updateUI(1, MAX_VALUE));
Scheduler.add(updateUI(2, MAX_VALUE));
Scheduler.add(updateUI(3, MAX_VALUE));
Scheduler.start()
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>
JavaScript には真のスレッド化はありません。JavaScript は柔軟な言語であるため、その一部をエミュレートすることができます。これは私が先日遭遇した例です。
Javascript には真のマルチスレッドはありませんがsetTimeout()
、非同期 AJAX 要求を使用して非同期動作を取得できます。
正確に何を達成しようとしていますか?
Javascriptでマルチスレッドをシミュレートする方法は次のとおりです
ここで、数値の加算を計算する 3 つのスレッドを作成します。数値は 13 で割ることができ、数値は 3 で割ることができ、10000000000 まで計算できます。これらの 3 つの関数は、並行性が意味するものと同時に実行することはできません。しかし、これらの関数を同時に再帰的に実行するトリックを紹介します: jsFiddle
このコードは私のものです。
体の部位
<div class="div1">
<input type="button" value="start/stop" onclick="_thread1.control ? _thread1.stop() : _thread1.start();" /><span>Counting summation of numbers till 10000000000</span> = <span id="1">0</span>
</div>
<div class="div2">
<input type="button" value="start/stop" onclick="_thread2.control ? _thread2.stop() : _thread2.start();" /><span>Counting numbers can be divided with 13 till 10000000000</span> = <span id="2">0</span>
</div>
<div class="div3">
<input type="button" value="start/stop" onclick="_thread3.control ? _thread3.stop() : _thread3.start();" /><span>Counting numbers can be divided with 3 till 10000000000</span> = <span id="3">0</span>
</div>
Javascript 部分
var _thread1 = {//This is my thread as object
control: false,//this is my control that will be used for start stop
value: 0, //stores my result
current: 0, //stores current number
func: function () { //this is my func that will run
if (this.control) { // checking for control to run
if (this.current < 10000000000) {
this.value += this.current;
document.getElementById("1").innerHTML = this.value;
this.current++;
}
}
setTimeout(function () { // And here is the trick! setTimeout is a king that will help us simulate threading in javascript
_thread1.func(); //You cannot use this.func() just try to call with your object name
}, 0);
},
start: function () {
this.control = true; //start function
},
stop: function () {
this.control = false; //stop function
},
init: function () {
setTimeout(function () {
_thread1.func(); // the first call of our thread
}, 0)
}
};
var _thread2 = {
control: false,
value: 0,
current: 0,
func: function () {
if (this.control) {
if (this.current % 13 == 0) {
this.value++;
}
this.current++;
document.getElementById("2").innerHTML = this.value;
}
setTimeout(function () {
_thread2.func();
}, 0);
},
start: function () {
this.control = true;
},
stop: function () {
this.control = false;
},
init: function () {
setTimeout(function () {
_thread2.func();
}, 0)
}
};
var _thread3 = {
control: false,
value: 0,
current: 0,
func: function () {
if (this.control) {
if (this.current % 3 == 0) {
this.value++;
}
this.current++;
document.getElementById("3").innerHTML = this.value;
}
setTimeout(function () {
_thread3.func();
}, 0);
},
start: function () {
this.control = true;
},
stop: function () {
this.control = false;
},
init: function () {
setTimeout(function () {
_thread3.func();
}, 0)
}
};
_thread1.init();
_thread2.init();
_thread3.init();
この方法が役立つことを願っています。
コードをステート マシンに変換するコンパイラであるNarrative JavaScriptを使用すると、スレッド化を効果的にエミュレートできます。これは、単一の線形コード ブロックで非同期コードを記述できるようにする "yielding" 演算子 ('->' と表記) を言語に追加することによって行われます。
今日出てくるはずの新しいv8エンジンはそれをサポートしています(私は思う)
生の Javascript でできる最善のことは、いくつかの非同期呼び出し (xmlhttprequest) を使用することですが、それは実際にはスレッド化ではなく、非常に制限されています。 Google Gearsはブラウザに多数の API を追加し、そのうちのいくつかはスレッドのサポートに使用できます。
AJAX を使用できない、または使用したくない場合は、iframe または 10 を使用してください。;) クロス ブラウザーに匹敵する問題やドット ネット AJAX などの構文の問題を心配することなく、マスター ページと並行して iframe でプロセスを実行できます。また、マスター ページの JavaScript (インポートした JavaScript を含む) をiframe。
たとえば、親 iframe でegFunction()
、iframe コンテンツがロードされたら親ドキュメントを呼び出す (これが非同期部分です)。
parent.egFunction();
必要に応じて、メインの html コードが iframe から解放されるように、iframe も動的に生成します。