0

I want to execute function on each processors.

Is OS X have any kernel function similar to on_each_cpu() in linux?

이유찬
  • 43
  • 4
  • 1
    If you’re just looking for some common Linux and macOS solution to this, I might consider [OpenMP](https://www.openmp.org/). But, in macOS, we’re generally abstracted away from this level of detail, e.g. routines like `concurrentPerform` are great at parallelizing routine across all available cores without risking thread explosion. Maybe you can tell us what the broader problem you’re really trying to solve and we might be able to advise you better. – Rob Mar 04 '20 at 20:09
  • 1
    @Rob: The question is not about functionality for *user space* applications but for OS **kernel**. In Linux kernel, `on_each_cpu` is used not for *speed-up* computations, but for **consolidate state** of all CPU's. E.g., for updating *per-CPU* variables. I guess the asker wants the function for similar purposes but in OS X kernel. – Tsyvarev Mar 04 '20 at 23:20
  • I'm not aware of any such function, certainly not with public KPI (usable by 3rd party kexts). Perhaps you could explain what you are trying to do and we can try to find a different solution? – pmdj Mar 09 '20 at 15:26

1 Answers1

0

You want the function mp_cpus_call:

/*
 * mp_cpus_call() runs a given function on cpus specified in a given cpu mask.
 * Possible modes are:
 *  SYNC:   function is called serially on target cpus in logical cpu order
 *      waiting for each call to be acknowledged before proceeding
 *  ASYNC:  function call is queued to the specified cpus
 *      waiting for all calls to complete in parallel before returning
 *  NOSYNC: function calls are queued
 *      but we return before confirmation of calls completing.
 * The action function may be NULL.
 * The cpu mask may include the local cpu. Offline cpus are ignored.
 * The return value is the number of cpus on which the call was made or queued.
 */
cpu_t
mp_cpus_call(
    cpumask_t       cpus,
    mp_sync_t       mode,
    void            (*action_func)(void *),
    void            *arg)

Note that it is not exported to kexts (or at least non-Apple ones) since it's gated behind com.apple.kpi.apple which is reserved for Apple kexts. You can still call this either by attempting to resolve the symbol at runtime or by trying to make your kext look like an Apple one (hard on macOS 11). I personlly use dynamic resolution but if this is a kext you want to ship you're mostly out of luck.

Allison
  • 2,213
  • 4
  • 32
  • 56