smartspawn/ts/smartipc.classes.thread.ts

61 lines
1.5 KiB
TypeScript
Raw Normal View History

2017-01-29 19:50:36 +00:00
import * as plugins from './smartipc.plugins'
import * as q from 'smartq'
2017-01-18 15:54:39 +00:00
2017-01-29 22:41:26 +00:00
import { Pool } from './smartipc.classes.pool'
2017-01-29 19:50:36 +00:00
export let setWorkerBasePath = (basePathArg: string) => {
plugins.threads.config.set({
basepath: {
node: basePathArg
}
})
2017-01-18 15:54:39 +00:00
}
export class Thread {
thread
2017-01-29 22:41:26 +00:00
workerPath: string
running: boolean = false
assignedPool: Pool = null
2017-01-29 19:50:36 +00:00
constructor(filePathArg: string) {
2017-01-29 22:41:26 +00:00
this.workerPath = filePathArg
2017-01-18 15:54:39 +00:00
}
/**
* sends a message to the spawned process
*/
2017-01-29 19:50:36 +00:00
send<T>(message: any): Promise<T> {
let done = q.defer<T>()
2017-01-29 22:41:26 +00:00
this.checkSpawn()
this.thread.send(message)
this.thread.on('message', (message: T) => {
done.resolve(message)
})
this.thread.on('done', (job, message: T) => {
2017-01-29 19:50:36 +00:00
done.resolve(message)
2017-01-29 22:41:26 +00:00
})
this.thread.on('error', err => {
2017-01-29 19:50:36 +00:00
done.reject(err)
})
return done.promise
2017-01-18 15:54:39 +00:00
}
2017-01-29 19:50:36 +00:00
kill() {
this.thread.kill()
2017-01-29 22:41:26 +00:00
this.running = false
}
assignToPool(poolArg: Pool) {
this.assignedPool = poolArg
2017-01-29 19:50:36 +00:00
}
2017-01-29 22:41:26 +00:00
private checkSpawn() {
if (!this.running && !this.assignedPool) {
this.running = true
this.thread = plugins.threads.spawn(this.workerPath)
} else if (!this.running && this.assignedPool) {
this.running = true
this.thread = this.assignedPool.run(this.workerPath)
}
}
}