What Should I use in Place of DispatchSource.makeMemoryPressureSource on Linux?

I'm working on modifying an SPM library so it can compile and run on Linux platforms, along with macOS. I am using Ubuntu Bionic with Swift 5.1.3.

In one of the computed properties, DispatchSource.makeMemoryPressureSource is used. Whenever I try to compile this on the Ubuntu platform, I get this compiler error:

error: type 'DispatchSource' has no member 'makeMemoryPressureSource'
        let source = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical])
                     ~~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~

Also, the type that the method returns (DispatchSourceMemoryPressure) apparently doesn't exist either.

What should I be using in place of this method on a Linux platform? Or maybe I am missing an import? I'm using both the Foundation and Dispatch modules.

You haven't done anything wrong, the memory pressure source does not exist on Linux in the general case. In principle some amount of this can be cobbled together with cgroups in cases where that is applicable, but broadly speaking the OOM killer on Linux does not give you a warning before it kills you, it just kills you.

Simply guard the code path with #if available and do not attempt to register the source on Linux is my recommendation.


For what it's worth, we've found that even on Darwin, 9 times out of 10 you get better behavior by not doing whatever you were doing in the memory pressure handler.

Just about the only good thing to do is set a flag that your code checks to see if it's ok to continue creating more stuff. It's almost never useful to actively try to free up memory.