Skip to content

Instantly share code, notes, and snippets.

@akira345
Created November 11, 2020 15:12
Show Gist options
  • Save akira345/09898dbfdef07af9963713b4b2291a6a to your computer and use it in GitHub Desktop.
Save akira345/09898dbfdef07af9963713b4b2291a6a to your computer and use it in GitHub Desktop.
mutexが必要??
'use strict';
const { Mutex } = require( 'await-semaphore' );
/**
* スリープ
*/
const _sleep = ( waitSec ) => {
return new Promise( function ( resolve ) {
setTimeout( function () { resolve(); }, waitSec );
} );
};
/**
* ダミー関数
* @param {*} val
*/
const f = async ( val ) => {
await _sleep( Math.random() * 1000 );
return val;
};
/**
* main
*/
const main = async () => {
// 戻り値格納配列
const retDatas = [];
// 処理データダミー
const dummyDatas = [];
const mutex = new Mutex();
for ( let i = 0; i <= 999999; ++i ) {
dummyDatas.push( i );
}
// 測定開始
var start = new Date();
await Promise.all(
dummyDatas.map( async ( val ) => {
const ret = await f( val );
// 共有変数を操作するのに排他制御が必要なのではないか?
mutex.use( async () => {
retDatas.push( ret );
} );
} )
);
/*
for ( const val of dummyDatas ) {
const ret = await f( val );
retDatas.push( ret );
}
*/
//結果
console.log( retDatas );
var end = new Date() - start;
console.info( 'Execution time: %dms', end );
};
// main
// 即時実行関数を定義
( async () => {
try {
await main();
} catch ( e ) {
}
} )();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment