[erlang-questions] How to get scheduler_id in nif?

Zhongzheng Liu liuzhongzheng2012@REDACTED
Tue Nov 8 03:11:10 CET 2016

If get scheduler_id in Erlang and pass it to nif, like this:

SID = erlang:system_info(scheduler_id),

I worry that after getting scheduler_id, the reductions run out and
the process may migrate to another scheduler. It may create a data

There is enif_make_unique_integer in OTP 19. Scheduler_id can be
extracted from unique integer.

Unfortunately enif_make_unique_integer is not available in OTP 18
which I am working on.

May be is possible to unbox a reference to extract scheduler_id ?

> I'm more inclined to ask why it is useful to know which scheduler_id a given process is being run on.

I am trying to make my nif lock free like erlang:make_ref/0 and
erlang:unique_integer/0 in OTP 18+

2016-11-07 18:34 GMT+08:00 Loïc Hoguin <essen@REDACTED>:
> On 11/07/2016 12:23 PM, Jesper Louis Andersen wrote:
>> On Sat, Nov 5, 2016 at 9:09 AM Sergej Jurečko <sergej.jurecko@REDACTED
>> <mailto:sergej.jurecko@REDACTED>> wrote:
>>     My suggestion is to call it from erlang when starting up your nif
>>     and save it to a thread local storage variable.
>> That sounds like a data race waiting to happen. If your process is moved
>> from one scheduler to another or if the scheduler you are running on are
>> taken offline by the operating system, you are in trouble.
>> I'm more inclined to ask why it is useful to know which scheduler_id a
>> given process is being run on.
> It is if you only send it on init. It's fine if you pass it in every call.
> For example you have N threads in the NIF, and use the scheduler id to pick
> the thread (works best when N = # of schedulers; often being the # of cores
> also). I do this in a customer project, it works very well. The trick is
> that it ultimately doesn't matter what number is passed, so it can change
> just fine.
> If you really need to know the scheduler of the calling process, afraid the
> only solution is to tie the process to a specific scheduler. But I wouldn't
> recommend it.
> --
> Loïc Hoguin
> https://ninenines.eu
> Author of The Erlanger Playbook,
> A book about software development using Erlang

More information about the erlang-questions mailing list