例证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
- [66] Oracle MTS模式下 进程地址与会话信
- [65] Go Reflect 性能
- [64] 如何拿下简短的域名
- [60] android 开发入门
- [59] 图书馆的世界纪录
- [59] 【社会化设计】自我(self)部分――欢迎区
- [58] IOS安全–浅谈关于IOS加固的几种方法
- [54] 视觉调整-设计师 vs. 逻辑
- [48] 读书笔记-壹百度:百度十年千倍的29条法则
- [47] 界面设计速成