技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> 其他 --> 例证NIF使用的误区

例证NIF使用的误区

浏览:677次  出处信息

NIF是什么? A NIF library contains native implementation of some functions of an Erlang module.
不清楚的同学请参考http://www.erlang.org/doc/man/erl_nif.html.
这个功能对于扩展Erlang,利用现有的遗留c的财产,提高性能非常有帮助.
但是通常同学们会无视手册里面的一句话:

Avoid doing lengthy work in NIF calls as that may degrade the responsiveness of the VM. NIFs are called directly by the same scheduler thread that executed the calling Erlang code. The calling scheduler will thus be blocked from doing any other work until the NIF returns

导致了非常严重的设计问题. 比如在NIF里面调用mysql client api, 作费时的IO操作等等, 我已经看到好几个同学这么干了,为了揭示这个问题的严重性, davisp同学为我们写了个例子来演示这个问题: 代码在这里

https://github.com/davisp/sleepy.

Sleepy - A misbehaving NIF
This demonstrates what happens if a NIF takes a long time and is called from as many schedulers as exist in the VM. Namely, that the VM is halted until the NIF functions return.

我们来演示下把:

git clone https://github.com/davisp/sleepy.git
Initialized empty Git repository in /tmp/sleepy/.git/
remote: Counting objects: 7, done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 7 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (7/7), done.
# cd sleepy
## 这个davisp同学是个Mac控, 我们在 linux下工作的, 需要修改下Makefile
# diff Makefile Makefile.orig
2c2
< INCLUDES = -I$(OTPROOT)/erts-5.7.5/include/
---
> INCLUDES = -I$(OTPROOT)/erts-5.8.2/include/
5c5
< GCCFLAGS = -O3 -fPIC -bundle -flat_namespace -undefined suppress -fno-common -Wall
---
> #GCCFLAGS = -O3 -fPIC -bundle -flat_namespace -undefined suppress -fno-common -Wall
8c8
< #GCCFLAGS = -O3 -fPIC -shared -fno-common -Wall
---
> GCCFLAGS = -O3 -fPIC -shared -fno-common -Wall
  
##david同学写的代码不够体贴人
# diff sleepy.erl  sleepy.erl.orig
6c6
<     erlang:load_nif("./sleepy", 0).
---
>     erlang:load_nif("sleepy", 0).
  
# 好吧, 编译运行
  
# make run
erl -noshell -s lockvm lock -s init stop
Starting heartbeat.
Tick
Tick
Tick
Tick
Locking the VM 从这开始你的VM被堵死
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Tick

我们可以看到NIF在sleep, 堵死了所有的调度器, 你的erlang VM也在睡觉, zZzZZz, 好舒服哦, 你的系统性能就惨了.

结论: 避免在NIF里面作费时的操作.

QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1