+static bool
+util_queue_create_thread(struct util_queue *queue, unsigned index)
+{
+ struct thread_input *input =
+ (struct thread_input *) malloc(sizeof(struct thread_input));
+ input->queue = queue;
+ input->thread_index = index;
+
+ queue->threads[index] = u_thread_create(util_queue_thread_func, input);
+
+ if (!queue->threads[index]) {
+ free(input);
+ return false;
+ }
+
+ if (queue->flags & UTIL_QUEUE_INIT_USE_MINIMUM_PRIORITY) {
+#if defined(__linux__) && defined(SCHED_IDLE)
+ struct sched_param sched_param = {0};
+
+ /* The nice() function can only set a maximum of 19.
+ * SCHED_IDLE is the same as nice = 20.
+ *
+ * Note that Linux only allows decreasing the priority. The original
+ * priority can't be restored.
+ */
+ pthread_setschedparam(queue->threads[index], SCHED_IDLE, &sched_param);
+#endif
+ }
+ return true;
+}
+
+void
+util_queue_adjust_num_threads(struct util_queue *queue, unsigned num_threads)
+{
+ num_threads = MIN2(num_threads, queue->max_threads);
+ num_threads = MAX2(num_threads, 1);
+
+ mtx_lock(&queue->finish_lock);
+ unsigned old_num_threads = queue->num_threads;
+
+ if (num_threads == old_num_threads) {
+ mtx_unlock(&queue->finish_lock);
+ return;
+ }
+
+ if (num_threads < old_num_threads) {
+ util_queue_kill_threads(queue, num_threads, true);
+ mtx_unlock(&queue->finish_lock);
+ return;
+ }
+
+ /* Create threads.
+ *
+ * We need to update num_threads first, because threads terminate
+ * when thread_index < num_threads.
+ */
+ queue->num_threads = num_threads;
+ for (unsigned i = old_num_threads; i < num_threads; i++) {
+ if (!util_queue_create_thread(queue, i))
+ break;
+ }
+ mtx_unlock(&queue->finish_lock);
+}
+