最近又写了一个多线程的小工具,对一些多线程的使用有了进一步的心得。
- Perl 创建线程有两种方式,正常通过threads->create 创建线程,用async 创建一个调用匿名过程的线程,具体参考perldoc threads。
- 线程共享变量需要使用 threads::shared,共享变量只能存储scalar,共享变量的引用,如果存储List Hash的引用需使用shared_clone([@list]) shared_clone({%hash})。
- 线程创建后最好join 或者detach,否则在退出时会有warning。
- 线程的join 方式,使用threads 中提供的函数接口,可以做到及时释放资源,参考下边的例子
use strict; use warnings; use threads; use Data::Dumper; $|=1; sub test{ my $i = shift; my @x = (1..); #使用一个大的变量观察内存使用情况 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? %s\n", $_->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.
仅供参考,欢迎指正。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233674.html原文链接:https://javaforall.net