LoginSignup
0
0

GoでGoroutine・Mutexのメモ

Posted at

はじめに

どうも僕です。
最近Goroutineを使った処理を書くことがあって、毎回うろ覚えだったのでメモしていきます。

Goroutine・Mutexについて

Goroutine(ゴルーチン)は言わずもがな、プログラムで並列に実行される作業単位のことです。
Goのいいところポイントの1つでもありますね。

MutexはGoroutineが同時に実行される場合、共有リソースへのアクセス制限・保護をするのがMutexです。

ゴルーチンで回す関数の中で特定のデータを更新していく場合、そのデータの競合を防ぐのがMutexってワケですな

サンプルコード

PlayGround

sample.go
package main

import (
	"fmt"
	"sync"
	"time"
)

var (
	mutex         sync.Mutex
	requestCount  int
	requestCount2 int
)

func main() {
	count := 0
	var wg sync.WaitGroup
	for count < 100 {
		wg.Add(1)
		go func(count int) {
			defer wg.Done()
			MutexTest()
            //NoMutexTest()
		}(count)
		count++
	}
	wg.Wait()
}

func NoMutexTest() {
	requestCount++
	fmt.Println("requestCount is: ", requestCount)
}

func MutexTest() {
	mutex.Lock()
	defer mutex.Unlock()
	requestCount2++
	fmt.Println("requestCount2 is: ", requestCount2)
}

解説

コードの内容としては、100回ループしてMutexがある関数とMutexがない関数で結果を見てみるコードです。
元々はAPIテスト用のモックサーバを作る際、リクエスト制限をつけるためにこのようなコードを作成しました。

MutexTest関数はmutex.Lockdefar mutex.Unlock()の二つがあります。

このLock・Unlockでデータの保護をするワケです。

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