129 lines
2.9 KiB
JavaScript
129 lines
2.9 KiB
JavaScript
"use strict";
|
|
|
|
import {Utils} from "../Utils/Utils.ecma.js";
|
|
import {ThreadModel} from "../Models/ThreadModel.ecma.js";
|
|
|
|
/**
|
|
* @typedef {import("../Application/AnP.ecma.js").AnP} AnP
|
|
*/
|
|
|
|
/**
|
|
* @callback anp_threads_manager_callback
|
|
* @param {!ThreadModel} thread
|
|
* @returns {void}
|
|
*/
|
|
|
|
/**
|
|
* @class
|
|
* @constructor
|
|
* @param {!AnP} anp
|
|
* @returns {void}
|
|
* @access public
|
|
*/
|
|
export const ThreadsManager = (function(){
|
|
|
|
/**
|
|
* @constructs ThreadsManager
|
|
* @param {!AnP} anp
|
|
* @returns {void}
|
|
* @access private
|
|
*/
|
|
const ThreadsManager = function(anp){
|
|
|
|
/** @type {ThreadsManager} */
|
|
const self = this,
|
|
/** @type {Array.<ThreadModel>} */
|
|
threads = [];
|
|
/** @type {boolean} */
|
|
let started = false,
|
|
/** @type {number|null} */
|
|
thread = null;
|
|
|
|
/**
|
|
* @returns {void}
|
|
* @access private
|
|
*/
|
|
const constructor = () => {
|
|
|
|
thread = setInterval(try_execute_threads, 1000 / 60);
|
|
|
|
};
|
|
|
|
/**
|
|
* @param {?anp_start_callback} callback
|
|
* @returns {boolean}
|
|
* @access public
|
|
*/
|
|
this.start = (callback = null) => {
|
|
|
|
/** @type {!anp_start_callback} */
|
|
const end = ok => {
|
|
Utils.execute(callback, ok);
|
|
return ok;
|
|
};
|
|
|
|
return end(started ? false : started = true);
|
|
};
|
|
|
|
/**
|
|
* @returns {void}
|
|
* @access private
|
|
*/
|
|
const try_execute_threads = () => {
|
|
threads.forEach(thread => {
|
|
thread && thread.try_execute();
|
|
});
|
|
};
|
|
|
|
/**
|
|
* @param {!anp_threads_manager_callback} callback
|
|
* @param {?(Object.<string, any|null>|Array.<any|null>)} inputs
|
|
* @returns {ThreadModel}
|
|
* @access public
|
|
*/
|
|
this.add = (callback, inputs = null) => {
|
|
|
|
/** @type {ThreadModel} */
|
|
const thread = new ThreadModel(anp, callback, inputs);
|
|
|
|
while(++ thread.i < threads.length)
|
|
if(!threads[thread.i])
|
|
break;
|
|
threads[thread.i] = thread;
|
|
|
|
return thread;
|
|
};
|
|
|
|
/**
|
|
* @param {!ThreadModel} thread
|
|
* @returns {void}
|
|
* @access public
|
|
*/
|
|
this.remove = thread => {
|
|
thread instanceof ThreadModel && threads[thread.i] && (threads[thread.i] = null);
|
|
};
|
|
|
|
/**
|
|
* @param {!ThreadModel} thread
|
|
* @returns {void}
|
|
* @access public
|
|
*/
|
|
this.play = thread => {
|
|
thread.working = true;
|
|
};
|
|
|
|
/**
|
|
* @param {!ThreadModel} thread
|
|
* @returns {void}
|
|
* @access public
|
|
*/
|
|
this.stop = thread => {
|
|
thread.working = false;
|
|
};
|
|
|
|
constructor();
|
|
|
|
};
|
|
|
|
return ThreadsManager;
|
|
})(); |