Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::TaskScheduler Class Reference

The TaskScheduler is responsible for managing tasks and threads. More...

#include <duckdb.hpp>

Collaboration diagram for duckdb::TaskScheduler:

Public Member Functions

 TaskScheduler (DatabaseInstance &db)
unique_ptr< ProducerToken > CreateProducer ()
void ScheduleTask (ProducerToken &producer, shared_ptr< Task > task)
 Schedule a task to be executed by the task scheduler.
void ScheduleTasks (ProducerToken &producer, vector< shared_ptr< Task > > &tasks)
bool GetTaskFromProducer (ProducerToken &token, shared_ptr< Task > &task)
 Fetches a task from a specific producer, returns true if successful or false if no tasks were available.
void ExecuteForever (atomic< bool > *marker)
 Run tasks forever until "marker" is set to false, "marker" must remain valid until the thread is joined.
idx_t ExecuteTasks (atomic< bool > *marker, idx_t max_tasks)
void ExecuteTasks (idx_t max_tasks)
 Run tasks until max_tasks have been completed, or until there are no more tasks available.
void SetThreads (idx_t total_threads, idx_t external_threads)
void RelaunchThreads ()
DUCKDB_API int32_t NumberOfThreads ()
 Returns the number of threads.
idx_t GetNumberOfTasks () const
idx_t GetProducerCount () const
idx_t GetTaskCountForProducer (ProducerToken &token) const
void Signal (idx_t n)
 Send signals to n threads, signalling for them to wake up and attempt to execute a task.
void SetAllocatorFlushTreshold (idx_t threshold)
 Set the allocator flush threshold.
void SetAllocatorBackgroundThreads (bool enable)
 Sets the allocator background thread.

Static Public Member Functions

static DUCKDB_API TaskScheduler & GetScheduler (ClientContext &context)
static DUCKDB_API TaskScheduler & GetScheduler (DatabaseInstance &db)
static void YieldThread ()
 Yield to other threads.
static idx_t GetEstimatedCPUId ()

Private Member Functions

void RelaunchThreadsInternal (int32_t n, bool destroy)

Private Attributes

DatabaseInstance & db
unique_ptr< ConcurrentQueue > queue
 The task queue.
mutex thread_lock
 Lock for modifying the thread count.
vector< unique_ptr< SchedulerThread > > threads
 The active background threads of the task scheduler.
vector< unique_ptr< atomic< bool > > > markers
 Markers used by the various threads, if the markers are set to "false" the thread execution is stopped.
atomic< idx_t > allocator_flush_threshold
 The threshold after which to flush the allocator after completing a task.
atomic< bool > allocator_background_threads
 Whether allocator background threads are enabled.
atomic< int32_t > requested_thread_count
 Requested thread count (set by the 'threads' setting).
atomic< int32_t > current_thread_count
 The amount of threads currently running.

Static Private Attributes

static constexpr int64_t TASK_TIMEOUT_USECS = 5000

Detailed Description

The TaskScheduler is responsible for managing tasks and threads.

Constructor & Destructor Documentation

◆ TaskScheduler()

duckdb::TaskScheduler::TaskScheduler ( DatabaseInstance & db)
explicit
335152 : db(db), queue(make_uniq<ConcurrentQueue>()),
335153 allocator_flush_threshold(db.config.options.allocator_flush_threshold),
335154 allocator_background_threads(Settings::Get<AllocatorBackgroundThreadsSetting>(db)), requested_thread_count(0),
335157}
atomic< idx_t > allocator_flush_threshold
The threshold after which to flush the allocator after completing a task.
Definition duckdb.hpp:26758
atomic< bool > allocator_background_threads
Whether allocator background threads are enabled.
Definition duckdb.hpp:26760
atomic< int32_t > current_thread_count
The amount of threads currently running.
Definition duckdb.hpp:26764
unique_ptr< ConcurrentQueue > queue
The task queue.
Definition duckdb.hpp:26750
void SetAllocatorBackgroundThreads(bool enable)
Sets the allocator background thread.
Definition duckdb.cpp:335369
atomic< int32_t > requested_thread_count
Requested thread count (set by the 'threads' setting).
Definition duckdb.hpp:26762

◆ ~TaskScheduler()

duckdb::TaskScheduler::~TaskScheduler ( )
335159 {
335160#ifndef DUCKDB_NO_THREADS
335161 try {
335162 RelaunchThreadsInternal(0, true);
335163 } catch (...) {
335164 // nothing we can do in the destructor if this fails
335165 }
335166#endif
335167}

Member Function Documentation

◆ GetScheduler() [1/2]

TaskScheduler & duckdb::TaskScheduler::GetScheduler ( ClientContext & context)
static
335169 {
335170 return TaskScheduler::GetScheduler(DatabaseInstance::GetDatabase(context));
335171}

◆ GetScheduler() [2/2]

TaskScheduler & duckdb::TaskScheduler::GetScheduler ( DatabaseInstance & db)
static
335173 {
335174 return db.GetScheduler();
335175}

◆ CreateProducer()

unique_ptr< ProducerToken > duckdb::TaskScheduler::CreateProducer ( )
335177 {
335178 auto token = make_uniq<QueueProducerToken>(*queue);
335179 return make_uniq<ProducerToken>(*this, std::move(token));
335180}

◆ ScheduleTask()

void duckdb::TaskScheduler::ScheduleTask ( ProducerToken & producer,
shared_ptr< Task > task )

Schedule a task to be executed by the task scheduler.

335182 {
335183 // Enqueue a task for the given producer token and signal any sleeping threads
335184 queue->Enqueue(token, std::move(task));
335185}

◆ ScheduleTasks()

void duckdb::TaskScheduler::ScheduleTasks ( ProducerToken & producer,
vector< shared_ptr< Task > > & tasks )
335187 {
335188 queue->EnqueueBulk(producer, tasks);
335189}

◆ GetTaskFromProducer()

bool duckdb::TaskScheduler::GetTaskFromProducer ( ProducerToken & token,
shared_ptr< Task > & task )

Fetches a task from a specific producer, returns true if successful or false if no tasks were available.

335191 {
335192 return queue->DequeueFromProducer(token, task);
335193}

◆ ExecuteForever()

void duckdb::TaskScheduler::ExecuteForever ( atomic< bool > * marker)

Run tasks forever until "marker" is set to false, "marker" must remain valid until the thread is joined.

335195 {
335196#ifndef DUCKDB_NO_THREADS
335197 static constexpr const int64_t INITIAL_FLUSH_WAIT = 500000; // initial wait time of 0.5s (in mus) before flushing
335198
335199 const auto &block_allocator = BlockAllocator::Get(db);
335200 const auto &config = DBConfig::GetConfig(db);
335201
335202 shared_ptr<Task> task;
335203 // loop until the marker is set to false
335204 while (*marker) {
335205 if (!block_allocator.SupportsFlush()) {
335206 // allocator can't flush, just start an untimed wait
335207 queue->semaphore.wait();
335208 } else if (!queue->semaphore.wait(INITIAL_FLUSH_WAIT)) {
335209 // allocator can flush, we flush this threads outstanding allocations after it was idle for 0.5s
335210 block_allocator.ThreadFlush(allocator_background_threads, allocator_flush_threshold,
335211 NumericCast<idx_t>(requested_thread_count.load()));
335212 auto decay_delay = Allocator::DecayDelay();
335213 if (!decay_delay.IsValid()) {
335214 // no decay delay specified - just wait
335215 queue->semaphore.wait();
335216 } else {
335217 if (!queue->semaphore.wait(UnsafeNumericCast<int64_t>(decay_delay.GetIndex()) * 1000000 -
335218 INITIAL_FLUSH_WAIT)) {
335219 // in total, the thread was idle for the entire decay delay (note: seconds converted to mus)
335220 // mark it as idle and start an untimed wait
335221 Allocator::ThreadIdle();
335222 queue->semaphore.wait();
335223 }
335224 }
335225 }
335226 if (queue->Dequeue(task)) {
335227 auto process_mode = TaskExecutionMode::PROCESS_ALL;
335228 if (Settings::Get<SchedulerProcessPartialSetting>(config)) {
335229 process_mode = TaskExecutionMode::PROCESS_PARTIAL;
335230 }
335231 auto execute_result = task->Execute(process_mode);
335232
335233 switch (execute_result) {
335234 case TaskExecutionResult::TASK_FINISHED:
335235 case TaskExecutionResult::TASK_ERROR:
335236 task.reset();
335237 break;
335238 case TaskExecutionResult::TASK_NOT_FINISHED: {
335239 // task is not finished - reschedule immediately
335240 auto &token = *task->token;
335241 queue->Enqueue(token, std::move(task));
335242 break;
335243 }
335244 case TaskExecutionResult::TASK_BLOCKED:
335245 task->Deschedule();
335246 task.reset();
335247 break;
335248 }
335249 } else if (queue->GetTasksInQueue() > 0) {
335250 // failed to dequeue but there are still tasks remaining - signal again to retry
335251 queue->semaphore.signal(1);
335252 }
335253 }
335254 // this thread will exit, flush all of its outstanding allocations
335255 if (block_allocator.SupportsFlush()) {
335256 block_allocator.ThreadFlush(allocator_background_threads, 0, NumericCast<idx_t>(requested_thread_count.load()));
335257 Allocator::ThreadIdle();
335258 }
335259#else
335260 throw NotImplementedException("DuckDB was compiled without threads! Background thread loop is not allowed.");
335261#endif
335262}
::int64_t int64_t
Here is the call graph for this function:

◆ ExecuteTasks() [1/2]

idx_t duckdb::TaskScheduler::ExecuteTasks ( atomic< bool > * marker,
idx_t max_tasks )

Run tasks until marker is set to false, max_tasks have been completed, or until there are no more tasks available. Returns the number of tasks that were completed.

335264 {
335265#ifndef DUCKDB_NO_THREADS
335266 idx_t completed_tasks = 0;
335267 // loop until the marker is set to false
335268 while (*marker && completed_tasks < max_tasks) {
335269 shared_ptr<Task> task;
335270 if (!queue->Dequeue(task)) {
335271 return completed_tasks;
335272 }
335273 auto execute_result = task->Execute(TaskExecutionMode::PROCESS_ALL);
335274
335275 switch (execute_result) {
335276 case TaskExecutionResult::TASK_FINISHED:
335277 case TaskExecutionResult::TASK_ERROR:
335278 task.reset();
335279 completed_tasks++;
335280 break;
335281 case TaskExecutionResult::TASK_NOT_FINISHED:
335282 throw InternalException("Task should not return TASK_NOT_FINISHED in PROCESS_ALL mode");
335283 case TaskExecutionResult::TASK_BLOCKED:
335284 task->Deschedule();
335285 task.reset();
335286 break;
335287 }
335288 }
335289 return completed_tasks;
335290#else
335291 throw NotImplementedException("DuckDB was compiled without threads! Background thread loop is not allowed.");
335292#endif
335293}
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ ExecuteTasks() [2/2]

void duckdb::TaskScheduler::ExecuteTasks ( idx_t max_tasks)

Run tasks until max_tasks have been completed, or until there are no more tasks available.

335295 {
335296#ifndef DUCKDB_NO_THREADS
335297 shared_ptr<Task> task;
335298 for (idx_t i = 0; i < max_tasks; i++) {
335299 queue->semaphore.wait(TASK_TIMEOUT_USECS);
335300 if (!queue->Dequeue(task)) {
335301 return;
335302 }
335303 try {
335304 auto execute_result = task->Execute(TaskExecutionMode::PROCESS_ALL);
335305 switch (execute_result) {
335306 case TaskExecutionResult::TASK_FINISHED:
335307 case TaskExecutionResult::TASK_ERROR:
335308 task.reset();
335309 break;
335310 case TaskExecutionResult::TASK_NOT_FINISHED:
335311 throw InternalException("Task should not return TASK_NOT_FINISHED in PROCESS_ALL mode");
335312 case TaskExecutionResult::TASK_BLOCKED:
335313 task->Deschedule();
335314 task.reset();
335315 break;
335316 }
335317 } catch (...) {
335318 return;
335319 }
335320 }
335321#else
335322 throw NotImplementedException("DuckDB was compiled without threads! Background thread loop is not allowed.");
335323#endif
335324}

◆ SetThreads()

void duckdb::TaskScheduler::SetThreads ( idx_t total_threads,
idx_t external_threads )

Sets the amount of background threads to be used for execution, based on the number of total threads and the number of external threads. External threads, e.g. the main thread, will also be used for execution. Launches total_threads - external_threads background worker threads.

335348 {
335349 if (total_threads == 0) {
335350 throw SyntaxException("Number of threads must be positive!");
335351 }
335352#ifndef DUCKDB_NO_THREADS
335353 if (total_threads < external_threads) {
335354 throw SyntaxException("Number of threads can't be smaller than number of external threads!");
335355 }
335356#else
335357 if (total_threads != external_threads) {
335358 throw NotImplementedException(
335359 "DuckDB was compiled without threads! Setting total_threads != external_threads is not allowed.");
335360 }
335361#endif
335362 requested_thread_count = NumericCast<int32_t>(total_threads - external_threads);
335363}

◆ RelaunchThreads()

void duckdb::TaskScheduler::RelaunchThreads ( )
335424 {
335425 lock_guard<mutex> t(thread_lock);
335426 auto n = requested_thread_count.load();
335427 RelaunchThreadsInternal(n, false);
335428}
mutex thread_lock
Lock for modifying the thread count.
Definition duckdb.hpp:26752

◆ NumberOfThreads()

int32_t duckdb::TaskScheduler::NumberOfThreads ( )

Returns the number of threads.

335332 {
335333 return current_thread_count.load();
335334}

◆ GetNumberOfTasks()

idx_t duckdb::TaskScheduler::GetNumberOfTasks ( ) const
335336 {
335337 return queue->GetTasksInQueue();
335338}

◆ GetProducerCount()

idx_t duckdb::TaskScheduler::GetProducerCount ( ) const
335340 {
335341 return queue->GetProducerCount();
335342}

◆ GetTaskCountForProducer()

idx_t duckdb::TaskScheduler::GetTaskCountForProducer ( ProducerToken & token) const
335344 {
335345 return queue->GetTaskCountForProducer(token);
335346}

◆ Signal()

void duckdb::TaskScheduler::Signal ( idx_t n)

Send signals to n threads, signalling for them to wake up and attempt to execute a task.

335374 {
335375#ifndef DUCKDB_NO_THREADS
335376 typedef std::make_signed<std::size_t>::type ssize_t;
335377 queue->semaphore.signal(NumericCast<ssize_t>(n));
335378#endif
335379}

◆ YieldThread()

void duckdb::TaskScheduler::YieldThread ( )
static

Yield to other threads.

335381 {
335382#ifndef DUCKDB_NO_THREADS
335383 std::this_thread::yield();
335384#endif
335385}

◆ SetAllocatorFlushTreshold()

void duckdb::TaskScheduler::SetAllocatorFlushTreshold ( idx_t threshold)

Set the allocator flush threshold.

335365 {
335367}
GMat threshold(const GMat &src, const GScalar &thresh, const GScalar &maxval, int type)

◆ SetAllocatorBackgroundThreads()

void duckdb::TaskScheduler::SetAllocatorBackgroundThreads ( bool enable)

Sets the allocator background thread.

335369 {
335371 Allocator::SetBackgroundThreads(enable);
335372}

◆ GetEstimatedCPUId()

idx_t duckdb::TaskScheduler::GetEstimatedCPUId ( )
static

Get the number of the CPU on which the calling thread is currently executing. Fallback to calling thread id if CPU number is not available. Result do not need to be exact 'return 0' is a valid fallback strategy

335387 {
335388#if defined(__EMSCRIPTEN__)
335389 // FIXME: Wasm + multithreads can likely be implemented as
335390 // return return (idx_t)std::hash<std::thread::id>()(std::this_thread::get_id());
335391 return 0;
335392#else
335393 // this code comes from jemalloc
335394#if defined(_WIN32)
335395 return (idx_t)GetCurrentProcessorNumber();
335396#elif defined(_GNU_SOURCE)
335397 auto cpu = sched_getcpu();
335398 if (cpu < 0) {
335399#ifndef DUCKDB_NO_THREADS
335400 // fallback to thread id
335401 return (idx_t)std::hash<std::thread::id>()(std::this_thread::get_id());
335402#else
335403
335404 return 0;
335405#endif
335406 }
335407 return (idx_t)cpu;
335408#elif defined(__aarch64__) && defined(__APPLE__)
335409 /* Other oses most likely use tpidr_el0 instead */
335410 uintptr_t c;
335411 asm volatile("mrs %x0, tpidrro_el0" : "=r"(c)::"memory");
335412 return (idx_t)(c & ((1 << 3) - 1));
335413#else
335414#ifndef DUCKDB_NO_THREADS
335415 // fallback to thread id
335416 return (idx_t)std::hash<std::thread::id>()(std::this_thread::get_id());
335417#else
335418 return 0;
335419#endif
335420#endif
335421#endif
335422}
Here is the caller graph for this function:

◆ RelaunchThreadsInternal()

void duckdb::TaskScheduler::RelaunchThreadsInternal ( int32_t n,
bool destroy )
private
335444 {
335445#ifndef DUCKDB_NO_THREADS
335446 auto &config = DBConfig::GetConfig(db);
335447 auto new_thread_count = NumericCast<idx_t>(n);
335448
335449 idx_t external_threads = 0;
335450 ThreadPinMode pin_thread_mode = ThreadPinMode::AUTO;
335451 if (!destroy) {
335452 // If we are destroying, i.e., calling ~TaskScheduler, we don't want to read the settings
335453 external_threads = Settings::Get<ExternalThreadsSetting>(config);
335454 pin_thread_mode = Settings::Get<PinThreadsSetting>(db);
335455 }
335456
335457 if (threads.size() == new_thread_count) {
335458 current_thread_count = NumericCast<int32_t>(threads.size() + external_threads);
335459 return;
335460 }
335461 if (threads.size() > new_thread_count) {
335462 // we are reducing the number of threads: clear all threads first
335463 for (idx_t i = 0; i < threads.size(); i++) {
335464 *markers[i] = false;
335465 }
335466 Signal(threads.size());
335467 // now join the threads to ensure they are fully stopped before erasing them
335468 for (idx_t i = 0; i < threads.size(); i++) {
335469 threads[i]->internal_thread->join();
335470 }
335471 // erase the threads/markers
335472 threads.clear();
335473 markers.clear();
335474 }
335475 if (threads.size() < new_thread_count) {
335476 // we are increasing the number of threads: launch them and run tasks on them
335477 idx_t create_new_threads = new_thread_count - threads.size();
335478
335479 // Whether to pin threads to cores
335480 static constexpr idx_t THREAD_PIN_THRESHOLD = 64;
335481 const auto pin_threads =
335482 pin_thread_mode == ThreadPinMode::ON ||
335483 (pin_thread_mode == ThreadPinMode::AUTO && std::thread::hardware_concurrency() > THREAD_PIN_THRESHOLD);
335484 for (idx_t i = 0; i < create_new_threads; i++) {
335485 // launch a thread and assign it a cancellation marker
335486 auto marker = unique_ptr<atomic<bool>>(new atomic<bool>(true));
335487 unique_ptr<thread> worker_thread;
335488 try {
335489 worker_thread = make_uniq<thread>(ThreadExecuteTasks, this, marker.get());
335490 if (pin_threads) {
335491 SetThreadAffinity(*worker_thread, NumericCast<int>(threads.size()));
335492 }
335493 } catch (std::exception &ex) {
335494 // thread constructor failed - this can happen when the system has too many threads allocated
335495 // in this case we cannot allocate more threads - stop launching them
335496 break;
335497 }
335498 auto thread_wrapper = make_uniq<SchedulerThread>(std::move(worker_thread));
335499
335500 threads.push_back(std::move(thread_wrapper));
335501 markers.push_back(std::move(marker));
335502 }
335503 }
335504 current_thread_count = NumericCast<int32_t>(threads.size() + external_threads);
335505 BlockAllocator::Get(db).FlushAll();
335506#endif
335507}
vector< unique_ptr< atomic< bool > > > markers
Markers used by the various threads, if the markers are set to "false" the thread execution is stoppe...
Definition duckdb.hpp:26756
vector< unique_ptr< SchedulerThread > > threads
The active background threads of the task scheduler.
Definition duckdb.hpp:26754
void Signal(idx_t n)
Send signals to n threads, signalling for them to wake up and attempt to execute a task.
Definition duckdb.cpp:335374

The documentation for this class was generated from the following files: