3
$\begingroup$

In a nutshell, how can I get this number:

enter image description here

I'm having trouble because $KernelID isn't a function and the FullForm is this crazy thing:

enter image description here

Motivation:

After you call CloseKernels[], the next time you LaunchKernels[] the new kernels don't start from one again:

enter image description here

In my parallel code I'd like to have access to the index of the kernel from 1 to $KernelCount, but I'm not sure how to efficiently get that:

offset = ToExpression@(StringCases[ToString[Kernels[][[1]]], NumberString][[1]])
(*Out[]= 17*)
$\endgroup$
5
  • 1
    $\begingroup$ What if you kept a variable where you stored the output of LaunchKernels, and referenced the kernels by their index (1-4) in that variable? I am sure there are practical, low-level reasons why the kernels continue to increment. $\endgroup$
    – ktm
    Commented Jan 23, 2020 at 20:29
  • 1
    $\begingroup$ Would 1 + Mod[$KernelID - 1, $KernelCount] do what you want? I.e., ParallelEvaluate[1 + Mod[$KernelID - 1, $KernelCount]] always gives, e.g., on a 4-core machine, {1,2,3,4}? $\endgroup$ Commented Jan 24, 2020 at 4:18
  • $\begingroup$ That won't always give the same values {3, 1, 2}, {2, 3, 1}, ... $\endgroup$
    – user5601
    Commented Jan 24, 2020 at 17:07
  • $\begingroup$ @user6014 the function I'm writing doesn't actually launch the kernels but uses ambient ones $\endgroup$
    – user5601
    Commented Jan 24, 2020 at 17:27
  • $\begingroup$ I deleted my comment. I misunderstood what you said in the original version of the question. Sorry. $\endgroup$
    – Szabolcs
    Commented Jan 24, 2020 at 20:41

1 Answer 1

3
$\begingroup$

You can use the internal, undocumented function Parallel`Developer`KernelID to do this:

LaunchKernels[3];
Parallel`Developer`KernelID /@ Kernels[]

{1, 2, 3}

Close kernels and try again:

CloseKernels[];
LaunchKernels[4];
Parallel`Developer`KernelID /@ Kernels[]

{4, 5, 6, 7}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.