@lakutata/core
Version:
Lakutata Framework Core
55 lines (49 loc) • 1.87 kB
text/typescript
import {Thread} from './Thread'
import {IThreadConstructor} from '../../interfaces/IThreadConstructor'
import {ThreadException} from '../../exceptions/ThreadException'
import {ProxyClass} from '../../lib/multipleRunner/definitions/interfaces/ProxyClass'
import {Thread as threadCreate} from '../../lib/multipleRunner/lib/Thread'
export class ThreadManager<TThread extends Thread = Thread> {
protected readonly threadMap: Map<IThreadConstructor<TThread>, TThread & ProxyClass> = new Map()
/**
* 创建线程
* @param {IThreadConstructor<TThread>} threadConstructor
* @returns {Promise<void>}
*/
public async createThread(threadConstructor: IThreadConstructor<TThread>): Promise<boolean> {
if (this.threadMap.has(threadConstructor)) return false
const threadProxy = await threadCreate(threadConstructor)
this.threadMap.set(threadConstructor, threadProxy)
return true
}
/**
* 判断线程是否存在
* @param {IThreadConstructor<TThread>} threadConstructor
* @returns {boolean}
*/
public has(threadConstructor: IThreadConstructor<TThread>): boolean {
return this.threadMap.has(threadConstructor)
}
/**
* 获取线程
* @param {IThreadConstructor<TThread>} threadConstructor
* @returns {TThread}
*/
public get(threadConstructor: IThreadConstructor<TThread>): TThread {
if (this.threadMap.has(threadConstructor)) {
return this.threadMap.get(threadConstructor) as TThread
}
throw new ThreadException(`Thread [${threadConstructor.name}] is not bound`)
}
/**
* 销毁线程
* @param {IThreadConstructor<TThread>} threadConstructor
* @returns {Promise<void>}
*/
public async destroy(threadConstructor: IThreadConstructor<TThread>): Promise<void> {
if (this.threadMap.has(threadConstructor)) {
await this.threadMap.get(threadConstructor)?.terminate()
this.threadMap.delete(threadConstructor)
}
}
}