例证NIF使用的误区
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 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里面作费时的操作.
扫一扫订阅我的微信号:IT技术博客大学习
- 作者:Yu Feng 来源: Erlang非业余研究
- 标签: NIF
- 发布时间:2011-01-20 22:34:29
-
[78] memory prefetch浅析
-
[55] 转载:cassandra读写性能原理分析
-
[54] 深入浅出cassandra 4 数据一致性问
-
[47] 基本排序算法的PHP实现
-
[46] 字符引用和空白字符
-
[43] JS中如何判断字符串类型的数字
-
[40] Inline Form Labels
-
[40] MySQL半同步存在的问题
-
[38] 获取Dom元素的X/Y坐标
-
[37] javascript插入样式