Skip to main content
coreydaley.dev

A job queue for C libraries that aren't thread-safe

Until June, Purrchiver ran one job at a time. Extracting a big archive while compressing a folder meant the compress sat in the queue. That was safe and simple, and slower than it needed to be on a Mac with many cores.

The obvious fix is to run N jobs at once. The catch is that two of the engines underneath can’t run concurrently in one process. That’s how the queue ended up with lanes, two priority tiers, and a fixed lock order.

Three engines, three answers

libarchive handles most formats (ZIP, 7z, tar and friends). Every open archive handle has its own state, so any number can run in parallel.

UnRAR, which Purrchiver uses for encrypted RAR, keeps process-wide state. Two sessions at once trample each other. From the start, my wrapper has held a process-wide lock for the life of a RAR session and failed fast if a second one tries to open:

UnRAR session already in flight on this process

That’s correct, but it’s not something a user should ever see.

Apple Archive (.aar, .aea) is the interesting one. Early on I read through the framework’s headers: streams carry their own thread count and caller-supplied callbacks, and I found no visible globals. I concluded it was safe per instance and let its tests run in parallel. A week later, two encode operations running at once, or an encode racing an extract, started failing intermittently with:

ArchiveError error 0

out of writeDirectoryContents. I added a process-wide lock around the whole framework pipeline for one operation: stream creation, the bulk call, and teardown. Locking only the bulk call wasn’t enough. Even the full lock didn’t make parallel test runs reliable, so the Apple Archive tests now run serially, and in the app the queue makes sure only one Apple Archive job runs at a time.

None of this comes from Apple’s documentation. It’s what I observed with my usage. The headers suggested one thing and testing showed another. I believed the testing.

Lanes

The queue gives each unsafe engine a lane. At most one admitted job may hold a given lane, and libarchive jobs need no lane at all, so they’re limited only by the overall job count.

Which lane a job needs comes from the file’s magic bytes, not its extension. A RAR renamed to .zip still detects as RAR and still waits for the UnRAR lane. Extension is only the fallback when there are no bytes to read yet, such as a compress job whose output doesn’t exist, or a file the sandbox won’t let me open yet. .rar, the old .r00–.r99 volume parts, .aar, and .aea map to their lanes.

Some jobs need two lanes. Saving an edited RAR as an Apple Archive reads through UnRAR and writes through the Archive framework, so that job holds both.

Global FIFO, but nothing waits on a lane it doesn’t need

The overall limit comes from a setting, “Maximum simultaneous operations”: Auto, 1, 2, 4, or 8, clamped to the core count. Auto is half the cores. That’s conservative on purpose: memory is the real constraint, since each extract can buffer up to a 1 GiB read cap. Setting it to 1 reproduces the old serial queue exactly.

Admission walks the waiting line front to back and admits every job that fits:

func pump() {
    var i = 0
    while i < waiters.count {
        let w = waiters[i]
        if running < limit && w.lanes.allSatisfy({ laneCount[$0, default: 0] == 0 }) {
            admit(w)                  // bump counts, then resume
            waiters.remove(at: i)
        } else {
            i += 1                    // blocked: skip it, keep looking
        }
    }
}

A RAR job stuck behind another RAR job doesn’t hold up the ZIP behind it. A later job never jumps an earlier one that could equally run. The limit is re-read on every admission, and changing the setting pumps the queue, so raising it starts waiting work right away. Lowering it never kills a running job.

Drag-out can’t wait in line

One kind of work can’t be queued at all. When you drag a file from an archive into Finder, Finder is waiting on the other end of the gesture. Putting that drag behind three batch extracts isn’t acceptable.

So under the queue there’s a second, process-wide gate per unsafe engine, with two waiting lines per lane:

  • Interactive: drag-outs. They skip the queue entirely and wait only for an operation already running on the same engine.
  • Batch: everything the queue admitted. Queued jobs take their lanes here too, at batch tier.

When a lane frees up, the interactive line drains first. Within each line, order is FIFO. That FIFO matters more than it sounds: if you drag three files in a row, they arrive in the order you dragged them, not the reverse. Your drags always outrank background work, and never outrank your own earlier drags.

func release(_ lane: Lane) {
    if !interactive[lane].isEmpty { interactive[lane].removeFirst().resume() }
    else if !batch[lane].isEmpty  { batch[lane].removeFirst().resume() }
    else                          { held[lane] = false }
}

Waiting is async, so no thread blocks while parked. The gate only brokers admission, and the work itself runs on the caller’s executor, so the gate’s actor never becomes a bottleneck.

Always take locks in the same order

Once one job can hold two lanes, deadlock is possible. Job A holds UnRAR and wants Apple Archive, while job B holds Apple Archive and wants UnRAR. The fix is the oldest one there is: lanes have a fixed order, and every multi-lane acquisition sorts first and releases in reverse. Two jobs can’t each be holding what the other needs.

Keep the old locks

The engine-level locks stayed: UnRAR’s fail-fast check and the Apple Archive lock. With the queue and gate in place they should never fire. If a future code path skips the queue, they turn a scheduling bug into a clean error or a short wait instead of corrupted output.

Gate waits are also logged and signposted. I haven’t built pause or preemption, such as suspending a batch job so a drag can start immediately, and I’d rather decide on that from real wait times than guess.

Tests that prove the rules

The tests cover lane exclusivity, lane-skip overtaking, a live limit raise, N=1 matching the old serial queue, and a multi-drag scenario: a running operation, then three drags, then a batch job, resolved in exactly that priority order. They also check that a misnamed RAR still lands in the UnRAR lane. To check that the tests can fail, I broke the code on purpose: removing the lane check fails the exclusivity tests, and flipping the tier priority fails the drag scenario.

The takeaway: when a library isn’t safe to run concurrently, make that a property of the scheduler. Decide the lane from content, not names. Give interactive work its own tier rather than a place in line. And when the documentation is silent, believe what you observe in testing over what the headers suggest.

Related posts