Perl threads 摘要
发布时间:2020-12-15 20:59:11 所属栏目:大数据 来源:网络整理
导读:最近又写了一个多线程的小工具,对一些多线程的使用有了进一步的心得。 Perl 创建线程有两种方式,正常通过threads-create 创建线程,用async ?创建一个调用匿名过程的线程,具体参考perldoc threads。 线程共享变量需要使用 threads::shared,共享变量只能
最近又写了一个多线程的小工具,对一些多线程的使用有了进一步的心得。
use strict; use warnings; use threads; use Data::Dumper; $|=1; sub test{ my $i = shift; my @x = (1..999999); #使用一个大的变量观察内存使用情况 sleep 2*$i; printf "%s run to the end.n",threads->tid(); } for (reverse (0..10)){ threads->create(&;test,$_); } my $monitor = async { #用来观察子线程状态 sleep 1; while(1){ for(threads->list()){ printf "%s join? %sn",$_->tid(),$_->is_joinable() ? 'true' : 'false'; } sleep 2; } }; $monitor->detach(); #方法1 $_->join() for threads->list() #方法2 #~ while(threads->list()){ #~ $_->join() for threads->list(threads::joinable); #~ }使用方法1 的结果,最先产生的线程耗时最长,按此法join 会按顺序释放资源,后来的线程虽已结束,但仍然等待前者结束然后才能释放自己的资源,前者结束前资源一直被占用。运行此脚本过程中打开任务管理器,观察内存使用情况,可以看到脚本结束前资源一直占用最大,没有释放过。 4 run to the end. 2 join? false 3 join? false 4 join? true 3 run to the end. 2 join? false 3 join? true 4 join? true 2 run to the end. 2 join? true 3 join? true 4 join? true 1 run to the end.使用方法2的结果,只join 已经完成的线程,资源会被及时释放。观察内存的使用情况,可以看到资源逐步递减,并没有被一直占用。 4 run to the end. 1 join? false 2 join? false 3 join? false 3 run to the end. 1 join? false 2 join? false 2 run to the end. 1 join? false 1 run to the end.仅供参考,欢迎指正。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |