Threads and object ownership
Which thread runs what, who owns each CEF object, and how pages and their clients fit together.
// Request filters run on Chromium's IO thread (CefIOActor): never block there.
profile.requestFilter = CefRequestFilter(hosts: ["example.com"]) { request in
request.method == "POST" ? .block : .allow
}
Object ownership
CEF objects are intrusively reference-counted.
- Structs CefSwift implements (clients, handlers, callbacks) come from
cefAllocate, which places a reference count and a retained Swift owner in a hidden header before the struct. Callbacks recover the owner withcefOwner. The owner is released when the count reaches zero. - Objects CEF returns are held in
CefRef, which releases them on deinit. - An object passed to a CEF function is consumed. An object returned by CEF, or passed into a CefSwift callback, arrives with a reference the receiver must release.
- An in-out object parameter, such as
cef_client_t** clientinon_before_popup, also arrives with a reference for the callback. CEF takes a reference back only for an object the callback puts in its place, so the callback releases the one it received either way. Missing this kept the opener’s client alive after every popup Chromium opened. - A callback that keeps such a reference across early returns holds it in
a
CefOwned, a non-copyable struct that releases it at the end of the scope unless a consuming method passed it to CEF, adopted it into aCefRefor released it. It costs no allocation. CefCensuscounts liveCefRefs by CEF type, implemented structs by owner type, received payloads and their shared memory mappings, and pending operations. It is off unless enabled (CefDiagnostics, SPI); SelfTest enables it and prints it after each group of checks.
Threads
Chromium’s UI thread is the app’s main thread, so SwiftUI and Chromium
share one thread, and the public API is @MainActor. CefMessagePump
puts Chromium’s work in the app’s run loop one of two ways
(Configuration.messageLoop).
Chromium’s own loop (.chromium, the default) is Chrome’s
arrangement. With external_message_pump off, Chromium’s main-thread
pump is MessagePumpCrApplication (CefApplication adopts
CrAppProtocol): a run loop source for posted work and a run loop timer
set to the next delayed task, both in the common modes, so the main
thread wakes exactly when work arrives or comes due, during menus,
window drags and modal sessions too, and not otherwise. That pump runs
work only while cef_run_message_loop() is on the stack. When the
runtime starts before the app’s run loop (from main, as CefSwiftApp
does), -[CefApplication run] calls cef_run_message_loop(), and
Chromium (MessagePumpNSApplication::DoRun) finds NSApp not running
and calls -[NSApplication run] itself, which reaches the override again
and runs AppKit’s loop: the stack Chrome has. stop: of that loop
returns from Chromium’s too, so the app’s run() returns as it would
without Chromium; a later run() starts both again. Started after
the app’s loop is running, CefMessagePump starts
cef_run_message_loop() from a one-shot run loop timer (default mode)
instead; Chromium then takes events itself with nextEventMatchingMask:
in the default mode, the app’s loop stays below it for the rest of the
process, and stop: of the app’s outermost loop does nothing
(CefApplication logs it). A timer rather than a block on the main
queue starts it: a block would hold the main queue, and the main actor
with it, for as long as the loop runs.
Quitting closes the pages, then calls cef_quit_message_loop(); the
loop returns once Chromium’s keep-alives are gone, AppKit’s loop runs
again, and terminate: runs again to shut Chromium down. Releasing the
last keep-alive makes Chromium post
NSApplicationWillTerminateNotification itself
(chrome::HandleAppExitingForPlatform); CefKit drops that one post, so
observers hear it once, from AppKit, after cef_shutdown().
CEF’s external pump (.external): cef_do_message_loop_work from a
one-shot run loop timer in the common modes, at the times
on_schedule_message_pump_work asks for. CEF reports work other threads
post, but not the timers Chromium’s main thread sets for itself while it
works, so the pump also looks on its own: 30 times a second for a quarter
of a second after each request, then every
EnergyPolicy.idleMessageLoopInterval. Each call polls for up to 10 ms
while a task is due within that time
(design notes).
CEF calls a few handlers on other threads. Where each arrives, from the C
API’s comments (CEF 158’s headers) and checked with cef_currently_on
and thread names at run time (CEF 156):
| Callback | Thread | CefKit |
|---|---|---|
cef_request_handler_t.get_resource_request_handler, cef_request_context_handler_t.get_resource_request_handler, cef_resource_request_handler_t.on_before_resource_load and get_resource_response_filter, cef_cookie_access_filter_t, cef_response_filter_t |
IO (Chrome_IOThread) |
The filter’s declarative match runs in C in get_resource_request_handler; the filter itself runs in on_before_resource_load, isolated to CefIOActor. |
cef_scheme_handler_factory_t.create |
IO | Creates the resource handler. |
cef_resource_handler_t.get_response_headers, cancel |
IO | Read and change the handler’s locked state. |
cef_resource_handler_t.open, skip, read |
Chromium’s thread pool (ThreadPoolForegroundWorker), in sequence |
open starts the CefSchemeHandler in a task; read reads a file, copies buffered bytes or waits for them. |
cef_request_handler_t.get_auth_credentials |
IO | Hops to the main actor for the delegate. CEF calls it only with --disable-chrome-login-prompt (CefRuntime.AuthenticationPromptPolicy.delegate, the default); without the switch Chromium shows its own dialog. |
cef_urlrequest_create; cef_urlrequest_client_t.on_request_complete, on_upload_progress, on_download_progress, on_download_data; cef_urlrequest_t.cancel |
The thread that created the request; CefKit creates it on IO (Chrome_IOThread, checked by thread name) |
cef_urlrequest_create needs a thread with a Chromium task runner and calls back on that thread, which alone may call cancel. URLRequestLoader is isolated to CefIOActor and creates requests there; callbacks enter it with CefIOActor.assumeIsolated. Progress closures run there. |
cef_urlrequest_client_t.get_auth_credentials |
IO, whatever thread created the request | Hops to the concurrent executor for RequestConfiguration.credential. |
cef_cookie_visitor_t.visit, cef_download_handler_t |
UI | No hop needed. |
cef_browser_process_handler_t.on_before_child_process_launch |
UI for a renderer, IO for the GPU process (per its header) | Reads only the app context’s immutable scheme list and appends to the command line; touches no actor-isolated state. |
cef_render_handler_t, cef_accessibility_handler_t, everything else |
UI | MainActor.assumeIsolated. |
on_schedule_message_pump_work |
Any | Posts to the main queue. |
Thread actors. CefIOActor and CefFileActor are global actors
whose executor, CefThreadExecutor, posts each job to a CEF thread with
cef_post_task: TID_IO, and TID_FILE_USER_VISIBLE, a sequence on
Chromium’s thread pool for blocking work. Its isolation checks
(checkIsolated(), isIsolatingCurrentContext()) ask
cef_currently_on, so a CEF callback on the IO thread is code isolated
to CefIOActor without a hop. The runtime asks an executor only from
macOS 15 on; CefIOActor.assumeIsolated and
CefFileActor.assumeIsolated check the thread themselves, so they work
on macOS 14 too.
Chromium’s task runners exist from on_context_initialized to the end of
cef_shutdown(). Outside that span, jobs run on a serial dispatch queue
of the executor’s own: before start-up at once; on start-up the queue
empties before jobs go to Chromium; from the moment CefRuntime begins
shutting down, jobs wait and run on the queue after cef_shutdown()
returns, once Chromium’s threads are gone. A job Chromium destroys without
running goes to the queue the same way. Each job is routed, and each
phase change made, under one lock, so a job always goes where the phase
at its submission sends it; the path that takes back a job Chromium
rejects inside cef_post_task never takes that lock. So no job is lost
or runs at the same time as another, and quitting waits for nothing.
Scheme handlers. A CefSchemeHandler runs with its own isolation:
nonisolated on Swift’s concurrent executor, or on CefIOActor or the
main actor if its type is isolated to one. Its body is data, a file or an
async sequence of Data. read reads a file with pread(2) straight
into the buffer CEF passes it, on the thread pool where CEF calls it and
where Chromium reads its own files. A sequence is iterated in a task, at
most 1 MB ahead of the page: a write waits until read drains the
buffer. read copies what is buffered, once, or, with nothing buffered,
keeps CEF’s buffer and callback until the next chunk arrives. A data
body is copied from the Data into CEF’s buffer, once per read. Chromium skips to the
start of a requested range itself, then serves the rest of the body with
the handler’s status, so CefKit answers single byte ranges completely
(206 with Content-Range and only the range’s bytes, or 416) and reports
Chromium’s skip as done.
The request filter was already synchronous on the IO thread, and the
scheme handler already answered off the main thread, so neither changed
the main thread’s work. A page that fetches 500 1 KB responses and one of
200 MB through a scheme handler, with a request filter on every request,
keeps the main thread busy for about 70 ms either way (Chromium’s own work
for the requests). The 200 MB body raised the app’s peak footprint by
194 MB as one Data, and by 12 MB as a stream or a file, in the same
time (about 200 ms).
The renderer side runs on the renderer’s main thread (TID_RENDERER),
which is the helper process’s main thread, so its extensions are
@MainActor and CEF’s callbacks enter it with MainActor.assumeIsolated.
CEF 158’s cef_render_process_handler_t, as 156’s, reports only frames’ contexts
(on_context_created, on_context_released); it has no callbacks for
worker or service-worker contexts, so the renderer side has no worker
hooks.
A CefPage is created as a model and bound to a Chromium page when it
is first hosted. Each one gets a CefBrowserClient that owns its handler
structs. Pages that Chromium creates itself (popups, DevTools, tabs opened
from Chrome’s UI) share their opener’s client or the runtime’s default
client, so every callback looks up its CefPage by Chromium’s page
identifier in CefRuntime’s registry. Such pages are wrapped as they
appear: a popup inherits its opener’s delegate, which hears about it through
page(_:didOpen:). A page in one of Chromium’s own tabbed windows
arrives on the default client (get_default_client) without a browser
view, so CEF cannot move it into a CefWindow; it goes to
CefRuntime.onChromeTab when that is set, with its window kept off
screen until the handler answers. Its opener is the page whose
on_open_urlfrom_tab (⌘- and ⇧-clicks) or on_before_popup CefKit left
to Chromium just before, which CEF does not report itself. The rest are passed to CefRuntime.onPageCreated.
Policy callbacks that Chromium can wait on become async delegate methods:
the CEF callback object is kept alive in a Task and completed with the
delegate’s answer.
Some state has no CEF event of its own. favicon is downloaded with
download_image when the display handler reports the page’s icon
addresses. zoomLevel is read back with get_zoom_level after each
navigation, each zoom command and each change made through the property,
in every page, since Chromium keeps one level per site.