5.1 Overview
The core MuPDF library is designed for simplicity, portability, and ease of
integration. For all these reasons, it has no global variables, has no thread library
dependencies, and has a well defined exception system to handle runtime errors.
Nonetheless, in order to be as useful as possible, clearly the library must
have some state and needs to be able to take advantage of multi-threaded
environments.
The solution to these seemingly conflicting requirements is the Context
(fz_context).
Every caller to MuPDF should create a Context at the start of its use of the library,
and destroy it at the end. This Context (or one ‘cloned’ from it) will then be passed
in to every MuPDF API call.
-
Global State
- At its simplest, the Context contains global settings for the
library. For instance, the default levels of anti-aliasing used by the text
and line art rendering routines are set in the Context, as is the default
style sheet for EPUB or FB2 files. In addition, the library stores its own
private information there too.
-
Error handling
- All error handling within MuPDF is done using the
fz_try/fz_catch constructs; see chapter 6 Error handling for more
details.
These constructs can be nested, so rely on an exception stack maintained
within the context. As such it is vitally important that no two threads use
the same context at the same time. See section 5.4 Multi-threading for
more information.
-
Allocation
- When embedding MuPDF into a system it is often desirable to
control the allocators used. A set of allocator functions can be provided
to the Context at creation time, and all allocations will be performed
using these. See chapter 7 Memory Management and The Store for more
information.
-
The Store
- MuPDF uses a memory cache to aid performance, and to avoid
repeated decoding of resources from the file. The store is maintained using
the context, and shared between a context and its clones. See chapter 7
Memory Management and The Store for more information.
-
Multi-threading
- MuPDF does not rely on threading itself, but it can be
used in a multi-threaded environment to give significant performance
improvements. Any thread library can be used with MuPDF. A set of
locking/unlocking functions must be passed to the context at creation
time, and the library will use these to ensure it is thread safe. See
section 5.4 Multi-threading for more information.