perldoc threads ---- 英文的... ...
网上找不到中文全面介绍的,无奈,哥今天就来翻译一下。
<<=========================threads===========================>>
#!/usr/bin/perl use threads ('yield', 'stack_size' => 64*4096, 'exit' => 'threads_only', 'stringify'); sub start_thread { my @args = @_; print('Thread started: ', join(' ', @args), "\n"); } ##创建线程的方法 # my $thr = threads->create('func_name', ...); # my $thr = threads->create(sub { ... }, ...); # my $thr = threads->create(\&func, ...); # The "->new()" method is an alias for "->create()". my $thr = threads->create('start_thread', 'argument1', 'argument2'); #通过create创建线程。返回线程实例 $thr->join(); #等待线程结束 threads->create(sub { print("I am a thread\n"); })->join(); #创建一个线程,没有返回值。那这个线程实例如何访问呢? my $thr2 = async { foreach (@ARGS) { print"$_\n"; } }; #通过async使用匿名子例程创建线程 $thr2->join(); if (my $err = $thr2->error()) { warn("Thread error: $err\n"); } # 在隐式的列表环境中调用thread my $thr3 = threads->create(sub { return (qw/a b c/); }); # 在显式的列表环境中调用thread my $thr4 = threads->create({'context' => 'list'}, sub { return (qw/a b c/); }); # 由于创建线程时使用的子例程返回的是列表,所以这里的join函数返回的也是列表 my @results = $thr3->join(); print "@results\n"; # 把线程从主线程中分离出来 # $thr->detach(); ##报错:Cannot detach a joined thread,因为$thr已经调用过join() $thr4->detach(); ## $tid = $thr4->tid(); print "线程4ID:$tid\n"; # Get a thread's object $thr6 = threads->self(); $thr7 = threads->object($tid); # Get a thread's ID $tid = threads->tid(); $tid = "$thr7"; #根据线程实例获得线程ID # 给其他线程一个运行的机会 threads->yield(); yield(); # 返回未分离的线程列表 my @threads = threads->list(); my $thread_count = threads->list(); my @running = threads->list(threads::running); my @joinable = threads->list(threads::joinable); # 判断两个线程是相同 if ($thr4 == $thr2) { print "thread4 equals to thread2.\n"; } # 管理线程栈大小 $stack_size = threads->get_stack_size(); $old_size = threads->set_stack_size(32*4096); # Create a thread with a specific context and stack size my $thr5 = threads->create({ 'context' => 'list', 'stack_size' &