Recent Comments
Link
Recent Posts
Today
Total
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
관리 메뉴

Study Memory Work

[Go Lang] 고루틴 - 멀티코어, 클로저 사용하기 본문

Programing/Go

[Go Lang] 고루틴 - 멀티코어, 클로저 사용하기

Hera Choi 2023. 3. 6. 13:36

멀티코어 사용하기

runtime.GOMAXPROCS(runtime.NumCPU())
	// 현 시스템의 CPU 코어 갯수를 반환하여 runtime 설정
    
fmt.Println("Current System CPU : ", runtime.GOMAXPROCS(0))
	// runtime.GOMAXPROCS(0) --> 0을 파라미터로 넣으면 위에서 세팅한 값을 출력해줌

 

예제)

package main

import (
	"fmt"
	"math/rand"
	"runtime"
	"time"
)

func exe(name int) {
	r := rand.Intn(100)
	fmt.Println(name, " start : ", time.Now())
	for i := 0; i < 100; i++ {
		fmt.Println(name, " >>>>> ", r, i)
	}
	fmt.Println(name, " end : ", time.Now())
}

func main() {

	runtime.GOMAXPROCS(runtime.NumCPU()) 
	fmt.Println("Current System CPU : ", runtime.GOMAXPROCS(0))


	fmt.Println("Main Routine Start : ", time.Now())
	for i := 0; i < 100; i++ {
		go exe(i)
	}

	time.Sleep(5 * time.Second)
	fmt.Println("Main Routine End : ", time.Now())

}

 

클로저 사용하기

반복문 클로저는 일반적으로 즉시 실행. but 고루틴 클로저는 가장 나중에 실행됨(반복문 종료 후)

예)

func main() {
	runtime.GOMAXPROCS(2)

	s := "Goroutine Closure : "

	for i := 0; i < 1000; i++ {
		go func(n int) {
			fmt.Println(s, n, " - ", time.Now())
		}(i) // 반복문 클로저는 일반적으로 즉시 실행. but 고루틴 클로저는 가장 나중에 실행됨(반복문 종료 후)
	}
	time.Sleep(5 * time.Second)
}

출력 :  
(순서대로 실행되고 있지 않는 것을 확인할 수 있다.)

Goroutine Closure :  279  -  2023-03-06 13:33:07.164504 +0900 KST m=+0.002365418
Goroutine Closure :  453  -  2023-03-06 13:33:07.164505 +0900 KST m=+0.002366626
Goroutine Closure :  280  -  2023-03-06 13:33:07.164506 +0900 KST m=+0.002367418
Goroutine Closure :  454  -  2023-03-06 13:33:07.164507 +0900 KST m=+0.002368543
Goroutine Closure :  281  -  2023-03-06 13:33:07.164508 +0900 KST m=+0.002369335
Goroutine Closure :  282  -  2023-03-06 13:33:07.16451 +0900 KST m=+0.002371168
Goroutine Closure :  283  -  2023-03-06 13:33:07.164512 +0900 KST m=+0.002373293
Goroutine Closure :  284  -  2023-03-06 13:33:07.164514 +0900 KST m=+0.002375001
Goroutine Closure :  457  -  2023-03-06 13:33:07.164515 +0900 KST m=+0.002376751
Goroutine Closure :  285  -  2023-03-06 13:33:07.164515 +0900 KST m=+0.002376668
Goroutine Closure :  286  -  2023-03-06 13:33:07.164518 +0900 KST m=+0.002378876
Goroutine Closure :  312  -  2023-03-06 13:33:07.164578 +0900 KST m=+0.002439210
...