Threading and Tasks in Chrome - FAQ

Note: Make sure to read the main Threading and Tasks docs first.

General

On which thread will a task run?

A task is posted through the base/task/post_task.h API with TaskTraits.

  • If TaskTraits contain BrowserThread::UI:

    • The task runs on the main thread.
  • If TaskTraits contain BrowserThread::IO:

    • The task runs on the IO thread.
  • If TaskTraits don't contain BrowserThread::UI/IO:

    • If the task is posted through a SingleThreadTaskRunner obtained from CreateSingleThreadTaskRunner(..., mode):

      • Where mode is SingleThreadTaskRunnerThreadMode::DEDICATED: * The task runs on a thread that only runs tasks from that SingleThreadTaskRunner. This is not the main thread nor the IO thread.

      • Where mode is SingleThreadTaskRunnerThreadMode::SHARED: * The task runs on a thread that runs tasks from one or many unrelated SingleThreadTaskRunners. This is not the main thread nor the IO thread.

    • Otherwise:

      • The task runs in a thread pool.

As explained in Prefer Sequences to Threads, tasks should generally run on a sequence in a thread pool rather than on a dedicated thread.

Does release of a TaskRunner block on posted tasks?

Releasing a TaskRunner reference does not wait for tasks previously posted to the TaskRunner to complete their execution. Tasks can run normally after the last client reference to the TaskRunner to which they were posted has been released and it can even be kept alive indefinitely through SequencedTaskRunnerHandle::Get() or ThreadTaskRunnerHandle::Get().

If you want some state to be deleted only after all tasks currently posted to a SequencedTaskRunner have run, store that state in a helper object and schedule deletion of that helper object on the SequencedTaskRunner using base::OnTaskRunnerDeleter after posting the last task. See example CL. But be aware that any task posting back to its “current” sequence can enqueue itself after that “last” task.