0

I need to use a serial queue in my code. I found a queue implementation made by @jessetane which is used by a huge amount of projects. Does anyone know if setting the concurrency param to 1 would essentially make the queue serial and synchronous? Thank you

1
  • why would you need such a queue to be synchronous? Commented Jan 5, 2023 at 21:28

2 Answers 2

1

setting the concurrency param to 1 would essentially make the queue serial and synchronous?

It would make it serial in the sense that the first job needs to complete first before the second will start.

But it will not make it synchronous -- which is a good thing.

For instance, if you had set concurrency to 1, and would execute the following:

q.push(function (cb) {
  setTimeout(function () {
    console.log('slow job finished')
    cb()
  }, 200)
})

q.push(function (cb) {
  console.log('simple')
  cb();
})

...then you can be assured that the output will have this order:

slow job finished
simple

This is the serial characteristic, but it is not synchronous. If you would have one more output statement, like here:

q.push(function (cb) {
  setTimeout(function () {
    console.log('slow job finished')
    cb()
  }, 200)
})

q.push(function (cb) {
  console.log('simple')
  cb();
})

console.log('hello')

...then the output will have:

hello
slow job finished
simple

This shows that the jobs are executed asynchronously, i.e. after the current call stack has been emptied.

Sign up to request clarification or add additional context in comments.

Comments

1

I think you misunderstand why this queue is set up as asynchronous

The point of having the queue be asynchronous is so you can wait for a new item to be added to the queue, and in the meantime JavaScript (which commonly uses a single thread) can be free to do other things than just wait for an item to appear on the queue

2 Comments

Oh ok, makes sense. Do you know if the the concurrency param is set to 1 the tasks passed to the queue are ensured to be processed serially?
If you RTFM, it says "q.concurrency Max number of jobs the queue should process concurrently, defaults to Infinity." So the answer is that the queue will always process jobs serially; the only thing concurency does list limit the max length of the queue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.