0
0

More than 3 years have passed since last update.

【Golang】サードパーティー semaphore

Posted at

【Golang】サードパーティー semaphore

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main 
/*
Semaphore

並列処理

インストール 済
https://godoc.org/golang.org/x/sync/semaphore
go get "golang.org/x/sync/semaphore"
*/

import (
    "context"
    "fmt"
    "time"

    "golang.org/x/sync/semaphore"
)

//2
//ここがセマフォ
//semaphoreで同時に走らせる数指定 == 1 開始する数
var s *semaphore.Weighted = semaphore.NewWeighted(1)


//3
func longProcess(ctx context.Context) {
    //3-2 キャンセル
    //goroutinを検証
    //1つならTrue
    //2つならFalse
    isAcquire := s.TryAcquire(1)

    //待っているgoroutinがあったら、キャンセル
    //2つ以上走っていたら、キャンセルする
    if !isAcquire {
        //ロックされていない
        fmt.Println("ロックされていない")
        return 
    }

    //3-1 ロック 待つ
    /*
        //errがnilでなければ
        //err := s.Acquire(ctx, 1); でロックする
        //このプロセスが終わったらリリースする。この間、他のgoroutinは待っている
        //一つずつしか走らせることができない
        if err := s.Acquire(ctx, 1); err != nil{
            //出力して終了する
            fmt.Println(err)
            return
        }
    */

    //1つずつ処理
    defer s.Release(1)
    fmt.Println("Wait...")
    time.Sleep(1 * time.Second)
    fmt.Println("Done")
}

func main() {
    //処理未定義 TODO部に設定できる事はまた調査する
    ctx := context.TODO()

    //並列処理
    //3つのgoroutin
    go longProcess(ctx)
    go longProcess(ctx)
    go longProcess(ctx)

    time.Sleep(5 * time.Second)

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0