Perl的线程系统如何工作? [英] How does Perl's threading system work?
问题描述
Perl的文档说: 自Perl 5.8起,使用称为解释器线程的模型进行线程编程,该模型为每个线程提供了新的Perl解释器.
在下面的程序中使用ps -Lm <pid>
,我可以看到线程并行运行,即它们在不同的内核中同时运行.但是,即使有4个线程(3个和主线程),ps aux
也仅显示一个Perl进程.
Using ps -Lm <pid>
with the program below I can see that threads run in parallel, i.e., they are being run at the same time in different cores. But even when there are 4 threads (3 and the main) ps aux
shows only one Perl process.
- 这是否意味着每个线程上都有一个完整的 Perl解释器?
- Perl线程是否映射到系统线程?
- 如果2为true,那么如何在单个进程中拥有多个Perl解释器?
- Does this mean that there is a whole Perl interpreter on each thread?
- Are Perl threads mapped to system threads?
- If 2 is true, how is possible to have multiple Perl interpreters within a single process?
use threads;
$thr = threads->new(\&sub1);
$thr2 = threads->new(\&sub1);
$thr3 = threads->new(\&sub1);
sub sub1 {
$i = 0;
while(true){
$i = int(rand(10)) + $i;
}
}
$thr->join;
推荐答案
"Perl解释器"是指执行Perl代码的环境.从用户的角度来看,主要是符号表及其中的全局变量,但它还包含许多内部变量(例如,在解析过程中使用的变量,当前操作等).
"Perl interpreter" refers to the environment in which the Perl code executes. From a user's perspective, that's mostly the symbol table and the globals therein, but it also includes a slew of internal variables (e.g. those used during parsing, the current op, etc).
-
是的,每个线程都有一个Perl解释器.
Yes, there's a Perl interpreter for each thread.
是的,Perl线程是系统线程.
Yes, Perl threads are system threads.
将"Perl解释器"视为可以创建任意数量实例的类.* Perl将其称为 perlembed .
Think of "Perl interpreter" as a class of which you can make any number of instances.* Perl refers to this as Multiplicity. See perlembed for how to embed a Perl interpreter in your application.
*—在构建Perl时需要使用-Dusemulitplicity
,这是-Dusethreads
所隐含的,这是向Perl中添加线程支持的方式.否则,将使用一堆全局变量而不是类".
* — Requires the use of -Dusemulitplicity
when building Perl, which is implied by -Dusethreads
, which is how thread support is added to Perl. Otherwise, a whole bunch of globals are used instead of a "class".
这篇关于Perl的线程系统如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!