0.0.5 • Published 3 years ago

@typeshell/promise v0.0.5

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

promise-utils

install

npm install @typeshell/promise --save

功能

sleep函数,以及可中断

我可以提供一个 naive版本的

const p = sleep(3000)
setTimeout(() => p.interrupt(), 1000)
await p // one second it will be interrupted

sleep的返回的对象本质是一个可中断的TimeoutPromise

BlockingQueue

import { BlockingQueue, sleep } from "../src"

const waitRandomly = () => sleep(Math.trunc(Math.random() * 100 + 30))

const bq = new BlockingQueue<number>(1)
const n = 10

const producer_main = async () => {
    try {
        for (let i = 0; i < n; ++i) {
            console.log(`put: ${i}`)
            await bq.put(i)
            console.log(`put.result: ${i}`)
            await waitRandomly()
        }
        bq.shutdown()
        console.log("producer_main: shutdown")
    } catch (ex) {
        console.log(ex)
    }
}
producer_main()

const consumer_main = async () => {
    try {
        for (let i = 0; i < n + 10; ++i) {
            console.log(`take.ready: ${i}`)
            // console.log(bq)
            const e = await bq.take()
            console.log(`take.result: ${i} ${JSON.stringify(bq.data)}`)
            await waitRandomly()
        }
        console.log("consumer_main: shutdown")
    } catch (ex) {
        console.log("Get shutdown error")
        console.log(ex)
    }
}
consumer_main()

ExecutorQueue

其它

为什么不做n2n队列

  1. 生产者蜂拥而至,处于await状态,此时其实排在系统内部的队列,本质与我们放在队列排队,无性能区别
  2. 多个生产者在等候,如果无队列化,一定会出现争抢,效率不高

因此 n2n 就用 n->1 以及 1->n 来模拟,避免性能

特性:

  1. n个prodcuer,n个consumer n个prodcuer会

  2. 设置是否blocking

  3. 传入函数,n个兑现
  4. consumer.take

测试

采用长度为1的blockingqueue,非常容易重现死锁的问题

0.0.5

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago

0.0.0

3 years ago