いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-351 (sync.OnceFunc)(go 1.21から追加)

関連記事

GitHub - devlights/blog-summary: ブログ「いろいろ備忘録日記」のまとめ

概要

以下、自分用のメモです。忘れない内にメモメモ。。。

Go 1.21 から、syncパッケージに OnceFunc って関数が追加されていたのですね。知らなかったです。

https://pkg.go.dev/sync@go1.21.4#OnceFunc

元々存在していた sync.Once が使いやすくなった感じですね。動きとしては同じで1度だけ実行される関数にしてくれます。

サンプル

package syncs

import (
    "runtime"
    "sync"

    "github.com/devlights/gomy/output"
)

// UseOnceFunc は、Go 1.21 で追加された sync.OnceFunc() のサンプルです。
//
// # REFERENCES
//   - https://pkg.go.dev/sync@go1.21.4#OnceFunc
func UseOnceFunc() error {
    //
    // Go 1.21 にて、sync.OnceFunc() が追加された
    // 元々存在していた、sync.Once を使いやすくした感じ
    //

    var (
        v = 0
        f = sync.OnceFunc(func() {
            v++
        })
    )
    output.Stdoutl("[before]", v)

    var (
        numCpu = runtime.NumCPU()
        done   = make(chan bool, numCpu)
    )
    for i := 0; i < numCpu; i++ {
        i := i
        go func() {
            f()
            done <- true
            output.Stderrf("[done]", "goroutine-%d\n", i)
        }()
    }

    for i := 0; i < numCpu; i++ {
        <-done
    }

    output.Stdoutl("[after]", v)

    return nil
}

実行すると以下のようになります。

$ task
task: Task "build" is up to date
task: [run] ./try-golang -onetime

ENTER EXAMPLE NAME: syncs_use_oncefunc

[Name] "syncs_use_oncefunc"
[before]             0
[done]               goroutine-15
[done]               goroutine-4
[done]               goroutine-2
[done]               goroutine-3
[done]               goroutine-0
[done]               goroutine-5
[done]               goroutine-6
[done]               goroutine-7
[done]               goroutine-8
[done]               goroutine-14
[done]               goroutine-10
[done]               goroutine-9
[done]               goroutine-13
[done]               goroutine-11
[done]               goroutine-1
[done]               goroutine-12
[after]              1


[Elapsed] 466.44µs

参考情報

sync: add OnceFunc, OnceValue, OnceValues · Issue #56102 · golang/go · GitHub

New functions to support sync.Once | by Pranoy Kundu | Oct, 2023 | Medium

Goのおすすめ書籍

Go言語による並行処理

Go言語による並行処理

Amazon


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。