1. 程式人生 > 其它 >[ Perl ] 多執行緒併發程式設計

[ Perl ] 多執行緒併發程式設計

https://www.cnblogs.com/yeungchie/

記錄一些常用的 模組 / 方法 。

多執行緒

使用模組 threads

use 5.010;
use threads;

sub func {
  my $id = shift;
  sleep 1;
  print "This is thread - $id\n";
}

建立執行緒

  • new
sub start {
  my $id = shift;
  my $t = new threads \&func, $id;
  return $t;
}
  • create
sub start {
  my $id = shift;
  my $t = new threads \&func, $id;
  return $t;
}
  • async
sub start {
  my $id = shift;
  my $t = async { &func( $id ) };
  return $t;
}

執行緒收屍

  • 阻塞 join
&start( 'join' )->join;
say 'Done';

This is thread - join
Done
# 父執行緒被子執行緒阻塞,成功收屍。

  • 非阻塞 detach
&start( 'detach' )->detach;
say 'Done';

Done
# 由於非阻塞,父執行緒已經退出,子執行緒變成孤兒執行緒,無法收屍。

資料共享

使用模組 threads::shared

use threads::shared;

標記共享變數

有幾種不同的寫法

  • 依次標記 :shared
my $scalar :shared;
my @array  :shared;
my %hash   :shared;
  • 批量標記 :shared
my ( $scalar, @array, %hash ) :shared;
  • 用函式標記 share()
my ( $scalar, @array, %hash );
share $scalar;
share @array;
share %hash;

克隆 shared_clone

向共享的變數中加入新的元素時,需要注意的地方。

my @newArray = qw( YEUNG CHIE 1 2 3 );
my $clone = shared_clone [@newArray];
push @array, $clone;
$hash{ keyName } = $clone;

lock

多個執行緒同時編輯一個共享變數時,需要注意的地方。

經典的取錢問題:
1 - 輸出額度 $amount = 500
2 - func() 函式模擬取錢,每次取 300
3 - 當 $amount < 300 時,則無法取錢

  • 沒加鎖的情況
my $amount :shared = 500;

sub func {
    unless ( $amount < 300 ) {
        sleep 1;  # 睡眠一秒模擬延遲
        $amount -= 300;
    }
}

# 這裡兩個執行緒模擬,兩次取錢同時進行
my $t1 = new threads \&func;
my $t2 = new threads \&func;
$t1->join;
$t2->join;

say $amount;

-100
# 結果被取了兩次,剩餘額度為 -100

  • 加了鎖的情況

調整一下子函式 func(), 加個鎖。

...
sub func {
    lock $amount;
    unless ( $amount < 300 ) {
        sleep 1;
        $amount -= 300;
    }
}
...

200
# 結果正確

執行緒佇列

使用模組 Thread::Queue

use Thread::Queue;

建立佇列

my $queue = new Thread::Queue;

入隊 enqueue

my $var = 'YEUNG';
$queue->enqueue( $var );
$queue->enqueue( qw( CHIE 1 2 3 ) );

出隊 dequeue

  • 默認出隊一個專案
say $queue->dequeue;

YEUNG

  • 指定多個專案出隊
say for $queue->dequeue( 3 );

CHIE
1
2

非阻塞出隊 dequeue_nb

  • 如果是阻塞出隊
my $queue = new Thread::Queue qw( YEUNG CHIE );
say while $_ = $queue->dequeue;

YEUNG
CHIE
# 程式會卡在這裡,等待佇列中新的專案加入

  • 使用非阻塞出隊
my $queue = new Thread::Queue qw( YEUNG CHIE );
say while $_ = $queue->dequeue_nb;

YEUNG
CHIE

剩餘 pending

pending 方法可以返回未出隊的專案數量。

my $queue = new Thread::Queue qw( YEUNG CHIE );
say $queue->dequeue;
say $queue->pending;
say $queue->dequeue;
say $queue->pending;

YEUNG
1
CHIE
0

檢視 peek

只是看看但是不出隊。

my $queue = new Thread::Queue qw( YEUNG CHIE );
say $queue->peek;
say $queue->pending;
say $queue->peek( 2 );
say $queue->pending;

YEUNG
2
CHIE
2

入隊結束 end

除了上面用 dequeue_nb 非阻塞出隊,之外還可以用 end 方法來

my $queue = new Thread::Queue qw( YEUNG CHIE );
$queue->end;
say while $_ = $queue->dequeue;

# 這樣雖然沒有用 dequeue_nb 方法,程式也不會卡住了。

不過這個方法需要模組版本 >= 3.01,一般系統自帶 Perl 是不支援的,但是我們也可以自己來實現這個效果:

  • 共享變數

    共享一個全域性變數標記入隊結束。

    my $endFlag :shared;
    
  • 生產者執行緒

    當入隊結束時,$endFlag 賦值為真。

    $endFlag = 1;
    
  • 消費者執行緒

    迴圈操作非阻塞出隊。

    while ( 1 ) {
        my $item = $queue->dequeue_nb;
        if ( defined $item ) {
            say $item;
        }
        else {
            # 當出隊失敗且入隊結束時,退出迴圈
            last if $endFlag;
        }
    }
    

執行緒訊號量

使用模組 Thread::Semaphore

use Thread::Semaphore;

執行緒池

使用模組 Thread::Pool

use Thread::Pool;

參考資料/拓展