iosswiftconcurrencyswift-concurrencyswift6

mach_task_self_ is not concurrency-safe because it involves shared mutable state


I have a function that returns the memory use of a device. It uses mach_task_self_ which gives a warning that it is not concurrency-safe.

task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), intPtr, &count)

According to this answer you can import and mark as @preconcurrency however when I try this it doesn't work.

@preconcurrency import Darwin.Mach.mach_init

It says '@preconcurrency' attribute on module 'Darwin' has no effect

When I jump to the definition of mach_task_self_ it shows me it is in Darwin > Mach > mach_init


Solution

  • It seems like a @preconcurrency import won't work if the thing you are trying to access is also imported by another non-preconcurrency import. Presumably, you are also importing things like Foundation.

    If you put the import in a separate file,

    @preconcurrency import Darwin
    
    var machTaskSelf: mach_port_t {
        mach_task_self_
    }
    

    there is no warning.

    And now you can use this computed property elsewhere.

    task_info(machTaskSelf, task_flavor_t(TASK_VM_INFO), intPtr, &count)