👼

神話のプログラム言語 Odin Thread 前編

に公開

はじめに、こんなの書いて誰がわかるんだろうと、思いながら書いてます。
odinに限らずthread処理は、難しいと思います。慣れればたいした問題ではないですが、はじめての方にとっては、難しいかと思います。
また、Threadの説明は、説明する量も多くて、一回ではまとめきれませんでしたので、前半と後半に分けて記載します。

Thread処理

1.単純なThread処理

まず、簡単なスレッド処理として、何の受け渡しもない、ただスレッドを発生させるだけのプログラムを以下に作成してみました。これは、thread.create関数でスレッドを生成し、thread.start関数でスレッドを動かすだけのスレッド処理です。
(simpleディレクトリの中に、以下のmain.odinを作成して確認します。)

simple/main.odin
package main 

import "core:fmt"
import "core:time"    // 時間計測用にtimeライブラリをimport
import "core:thread"  // threadライブラリをimport

// スレッド実行時のワーカー
worker_proc :: proc ( t : ^thread.Thread ) {
  fmt.printfln("thread%v start.", t.user_index)
  // 実際はここで何らかの処理を行う
  time.sleep(300 * time.Millisecond)
  fmt.printfln("thread%v end.", t.user_index)
}

// メイン処理 スレッドを発生させて終わるだけのプログラム
main :: proc() {
  threads := make( [ dynamic ]^thread.Thread )  // thread配列を作成
  defer delete( threads )

  num_threads := 5
  for i in 0 ..< num_threads {          // 5つのスレッドを生成し実行する
    t := thread.create( worker_proc )   // スレッドの生成
    t.init_context = context            // 現状のコンテキスト情報を設定
    t.user_index = i                    // スレッドIDの設定
    append( &threads, t )
    thread.start( t )                   // スレッドの起動
  }

  // 全てのスレッドが終了するまで待機
  for t in threads {                    // 動的配列からスレッドを取り出す
    thread.join( t )                    // スレッドの待機
    thread.destroy( t )                 // スレッドの破棄
  }
}

このプログラムは、threadの動的配列を作成して、各thread毎にスレッドを発生させています。各スレッドには、現在のcontext情報とスレッドIDを渡して、スレッドを起動します。スレッド終了後はthread.join関数で待機させ後に、thread.destroy関数でスレッドを破棄させているだけのプログラムになります。
注意点として、Odinでは各スレッドに、init_context(現状のcontext)とuser_index(スレッドID)とdata(メインからの受け渡しエリア)を渡す事が出来ます。ここでは、contextとuser_indexだけを設定しています。dataに関しては、4.thread_groupによるThread処理を参照願います。

実行結果
$> odin run .\simple\
thread1 start.
thread0 start.
thread2 start.
thread3 start.
thread4 start.
thread3 end.   <= 300ミリ秒後に以下の表示が行われる
thread4 end.
thread2 end.
thread0 end.
thread1 end.

各スレッドは起動から300ミリ秒後にメッセージを表示して終了します。表示の順番については、同時並行で動作しているスレッドなので何が一番早いかはわかりません。

2.mutexによるThread処理

Mutexとは、グローバル変数値や同一ファイルへの同時書き込みを防ぐ制御のしくみの事です。
ここでは、10個のスレッドが、同じファイルに対して書き込みを行う処理を行っています。この場合、Mutexを使った、排他ロック(sync.lock)をかけて、同時に書き込みを起こさないようにします。
(mutexディレクトリの中に、以下のmain.odinを作成して確認します。)

mutex/main.odin
package main

import "core:fmt"
import "core:thread"
import "core:sync"
import "core:os"

MutexFileName :: "./mutex.txt"  // 各スレッドが書き込むファイル
MutexThreadLen :: 10            // スレッド数
myMutex :sync.Mutex             // 排他制御用のMutex変数をグローバルに設定

// メイン処理
main :: proc() {
  // スレッドの配列を作成した後、スレッドを起動
  threads := make( [dynamic]^thread.Thread, 0, MutexThreadLen )
  defer delete( threads )

  for i in 0 ..< MutexThreadLen {
    // mutex_workerスレッドの生成
    t := thread.create( mutex_worker )
    if thr != nil {
      // 値を設定したのに、スレッドを起動
      t.init_context = context
      t.user_index = i 
      append( &threads, t )
      thread.start( t )
    }
  }

  // 全てのスレッドが終了するまで待機
  for t in threads {    // 動的配列からスレッドを取り出す
    thread.join( t )    // スレッドの待機
    thread.destroy( t ) // スレッドの破棄
  }
}

// 排他スレッド処理
// グローバルmutex変数を使って、ロックを行う
mutex_worker :: proc(t: ^thread.Thread) {
  sync.lock( &myMutex ) // 排他ロックを行う

  fmt.printfln("work of t%d 開始", t.user_index)
  for i in 0 ..< 5 {  // 5回書き込み
    file_write( MutexFileName, t.user_index )
  }
  fmt.printfln("work of t%d 完了", t.user_index)

  sync.unlock( &myMutex ) // ロック解除を行う
}

// ファイルへの書き込み処理
file_write :: proc(filename: string, user_index: int) {
  buf : [128]byte

  if fd, ok := os.open( filename, os.O_CREATE | os.O_APPEND ); ok == nil {
    defer os.close( fd )

    str := fmt.bprintfln(buf[:], "thread[%02v]の書き込み", user_index) // C言語で言う所のsprintf関数
    b := transmute([]byte)str     // string -> []byte変換
    os.write( fd, b )
    os.flush( fd )
  }
}

上記プログラムでは、Threadの動的配列を10個作成し、10スレッドを同時に動作させています。各スレッド内では、一つのmutex.txtファイルに対して、5行書き込み終了すると言うだけのプログラムです。問題なのは、同じファイルに対して、同時に書き込みを行うため、mutex_worker関数を排他ロックしている事です。結果としては、順番に出力されているように見えると思います。

実行結果
$> odin run .\mutex\
work of t0 開始
work of t0 完了
work of t1 開始
work of t1 完了
~~~ 省略 ~~~
work of t9 開始
work of t9 完了
work of t8 開始
work of t8 完了

結果、当たり前ですが、開始と完了の表示結果が混じる事なく、対で表示されます。何故なら、ロックしているので、他のスレッドが動作待機しているためです。また、各スレッドで書き込むファイル(mutex.txt)の内容も排他ロックされているため順次10*5行の書き込みがされています。
※mutex_worker関数を排他ロックを削除して実行すると、スレッド書き込みの順番が乱雑に出力されます。

出力されるmutex.txt
thread[00]の書き込み
thread[00]の書き込み
~~~ 省略 ~~~
thread[08]の書き込み
thread[08]の書き込み

3.thread_local

Odinには@thread_local属性と言うのがあります。これは、スレッドごとに独立した値を保持することをコンパイラに指示するために使用されます。
以下の処理は、shared_counterに対して@thread_local属性を設定し、それぞれのスレッドでshared_counterを加算する処理を行っております。
(thread_localディレクトリの中に、以下のmain.odinを作成して確認します。)

thread_local/main.odin
package main

import "core:fmt"
import "core:thread"
import "core:time"

// 複数のスレッドで共有されるが、各スレッドは独自のコピーを持つ
// これは、マルチスレッド環境において、複数のスレッドがグローバル変数や静的変数にアクセスする際に、スレッド間でデータが競合しないようにするために使用されます。
@(thread_local)
shared_counter: int;  // thread_local属性のグルーバル変数

// メイン処理
main :: proc() {
  // メインスレッドの shared_counter は 0
  fmt.printf( "メインスレッドの初期値: %d\n", shared_counter )
    
  threads := make( [dynamic]^thread.Thread )
  defer delete( threads )

  num_threads := 5
  for i in 0 ..< num_threads {
    t := thread.create( local_worker_proc )
    t.init_context = context
    t.user_index = i
    append( &threads, t )
    thread.start( t )   // スレッドの開始
  }

  // 全てのスレッドが終了するまで待機
  for t in threads {    // 動的配列からスレッドを取り出す
    thread.join( t )    // スレッドの待機
    thread.destroy( t ) // スレッドの破棄
  }

  // メインスレッドの shared_counter は依然として変更されていない
  fmt.printf( "メインスレッドの最終値: %d\n", shared_counter )
}

// thread.createで実行されるタスク
local_worker_proc :: proc( t : ^thread.Thread ) {
    // このスレッドの shared_counter の値は、他のスレッドから見えない
    for i in 0 ..< 5 {
        shared_counter += 1
        time.sleep( 1 * time.Millisecond ) // 他のスレッドが動くのを許容
    }
    fmt.printf( "スレッド %d の最終カウンター値: %d\n", t.user_index, shared_counter )
}

結果を見てわかる通り、main関数内では、カウンター値が0のままで加算されていません。
何故なら、メインと各スレッド毎に異なるカウンター変数が設けられているためです。
@thread_localは競合を防ぐために、それぞれ異なるカウンター変数を設けるための属性です。(余り使い道はないように思います。)

実行結果
$> odin run .\thread_local\
メインスレッドの初期値: 0
スレッド 1 の最終カウンター値: 5
スレッド 4 の最終カウンター値: 5
スレッド 2 の最終カウンター値: 5
スレッド 3 の最終カウンター値: 5
スレッド 0 の最終カウンター値: 5
メインスレッドの最終値: 0

4.thread_groupによるThread処理

Wait_Groupとは、名前の通り、各スレッドをグループ化し、全てのスレッドが終了したかを確認する制御です。
今まで、動的配列を使ったスレッド制御を行ってきましたが、ここでは、sync.wait_group関数で各スレッドの終了と待機を行います。また、各スレッド内で、スレッドの終了を指示させるために、WaitGroupDataと言う構造体を、各スレッドのdata項目に設定してます。
(thread_groupディレクトリの中に、以下のmain.odinを作成して確認します。)

thread_group/main.odin
package main

import "core:fmt"
import "core:thread"
import "core:sync"
import "core:time"

// スレッドに渡す構造体
WaitGroupData :: struct { 
    loop: int,      // 各スレッドへの指定ループ回数を渡す
    res: string,    // スレッドから結果を返す
    waitgroup: ^sync.Wait_Group,
}

// メイン処理
main :: proc() {
  // fmt.tprintfでtemp_allocatorを使っているので最後にメモリ解放
  defer free_all( context.temp_allocator )

  wg : sync.Wait_Group

  // スレッドの生成とデータ作成
  t1 := thread.create( worker )
  t1.init_context = context
  t1.user_index = 1
  t1.data = &WaitGroupData{ loop = 8, res = "", waitgroup = &wg }

  t2 := thread.create( worker )
  t2.init_context = context
  t2.user_index = 2
  t2.data = &WaitGroupData{ loop = 5, res = "", waitgroup = &wg }

  t3 := thread.create( timeline )
  t3.init_context = context
  t3.user_index = 3
  t3.data = &WaitGroupData{ loop = 8, res = "", waitgroup = &wg }

  sync.wait_group_add( &wg, 3 )   // 3つのスレッドを動作させるので、引数3を設定

  // スレッドの開始
  thread.start( t1 )
  thread.start( t2 )
  thread.start( t3 )

  sync.wait_group_wait( &wg )     // 全てのthreadがsync.wait_group_doneまで待機

  value := (cast(^WaitGroupData)t1.data)
  fmt.println(value.res) // 結果を返せている
  value = (cast(^WaitGroupData)t2.data)
  fmt.println( value.res ) // 結果を返せている
  fmt.println( "thread終了" )
}

// workerスレッド 受け取ったループ数で表示出力を行うだけの処理
worker :: proc( t: ^thread.Thread ) {
  fmt.printfln( "workerスレッド( %d )の起動", t.user_index )

  thread_data := (cast(^WaitGroupData)t.data)
  for i in 0 ..< thread_data.loop {
    fmt.printfln( "work of thread %v done", t.user_index )
    time.sleep( 500 * time.Millisecond )
  }
  // main関数にメッセージを返す
  thread_data.res = fmt.tprintf( "workerスレッド( %v )の終了", t.user_index )

  // workerの最後に停止指示を送る
  sync.wait_group_done( thread_data.waitgroup )
}

// timelineスレッド 1秒毎に経過時間を表示するだけの処理
timeline :: proc( t: ^thread.Thread ) {
  thread_data := (cast(^WaitGroupData)t.data)
  for i in 0 ..< thread_data.loop {
    fmt.printfln( "----- 経過時間 %02v sec", i )
    time.sleep( time.Second )
  }
  // timelineの最後に停止指示を送る
  sync.wait_group_done( thread_data.waitgroup )
}

上記処理は、各スレッド毎に、実行時間(ループ回数)を渡して処理を行っています。また、timelineスレッドで1秒毎に時間の経過を表示させるようにしています。
sync.wait_group_add関数でスレッド数を設定し、sync.wait_group_wait関数で全てのスレッドが終わるまで待機を行っています。各スレッドには、sync.wait_group_done関数を行う事で、スレッドの完了がわかる仕組みとなります。
また、今回のスレッドではスレッドが完了通知を行うために、メイン処理からデータを受け渡しする為に、WaitGroupData構造体にデータを設定して渡しています。

実行結果
$> odin run .\thread_group\
workerスレッド( 2 )の起動
work of thread 2 done
workerスレッド( 1 )の起動
----- 経過時間 00 sec
work of thread 1 done
work of thread 1 done
work of thread 2 done
----- 経過時間 01 sec
work of thread 2 done
work of thread 1 done
work of thread 1 done
work of thread 2 done
----- 経過時間 02 sec
work of thread 2 done
work of thread 1 done
work of thread 1 done
----- 経過時間 03 sec
work of thread 1 done
work of thread 1 done
----- 経過時間 04 sec
----- 経過時間 05 sec
----- 経過時間 06 sec
----- 経過時間 07 sec
workerスレッド( 1 )の終了  <= wait終了後にスレッドから受け取ったデータを出力
workerスレッド( 2 )の終了
thread終了

上記結果から、スレッド1が8回繰り返し出力し、スレッド2が5回繰り返し出力しています。
また、3つのスレッドが終わった後に、スレッドから戻って来たデータ「workerスレッド( x )の終了」を出力させています。

おわりに

今回はthreadの簡単な使い方と、MutexとWaitGroupの使い方を説明しました。Threadプログラムでは、MutexやWaitGroupは、普通に使う機能ですので、覚えておいた方が良いのかもしれません。
次回は、スレッドプールとchannel送受信について説明していきます。

Discussion