[Go] 8장(완) 고루틴과 채널

1. 고루틴(goroutine)

고루틴은 Go에서 경량 스레드로, go 키워드를 사용해 함수를 비동기적으로 실행할 수 있게 해줍니다. 고루틴은 메모리 해드가 적고, 수천 개의 고루틴을 동시에 실행할 수 있습니다.

package main

import (
	"fmt"
	"time"
)

func sayHello(id int) {
	for i := 0; i < 5; i++ {
		fmt.Printf("Go %d: Hello %d\n", id, i)
		time.Sleep(time.Microsecond * 100) // 100초간 대기
	}
}

func main() {
	for i := 0; i < 3; i++ {
		go sayHello(i) // 고루틴 시작  
	}
	time.Sleep(time.Second * 2) // 메인 고루틴 대기
	fmt.Println("프로그램 종료")
}

2. 채널(channel)

채널은 고루틴 간의 데이터 통신을 위한 구조체로, 데이터의 송시과 수신을 안전하게 처리할 수 있게 해주며, 채널을 사용하면 고루틴 간에 데이터를 전송하고 동기화할 수 있습니다.

package main

import (
	"fmt"
)

func produce(ch chan<- int) {
	for i := 0; i < 5; i++ {
		ch <- i // 채널에 데이터 전송
	}
	close(ch) // 채널 닫기
}

func consume(ch <-chan int) {
	for value := range ch {
		fmt.Printf("소비된 값: %d\n", value)
	}
}

func main() {
	ch := make(chan int) // 채널 생성

	go produce(ch) // 생산자 고루틴 시작
	go consume(ch) // 소비자 고루틴 시작

	// 메인 고루틴 대기
	fmt.Scanln()
	fmt.Println("프로그램 종료")
}

요약

  • 고루틴: 비동기적으로 실행되는 경량 스레드.
  • 채널: 고루틴 간 데이터 통신을 위한 구조체
  • 예제: 고루틴을 사용해 동시성 프로그램을 작성, 채널을 통해 고루틴 간에 데이터를 전송하는 방법

New! . Go 웹개발 세팅하기

Go에서 웹개발을 하기 위해서는 go 라이브러리인 net/http를 사용해서 웹 개발을 할 수 있습니다. 먼저 프로젝트 폴더에main.go 파일을 생성해줍니다. 아래 예제 코드로 go 웹 코드를 작성해줍니다.

package main

import (
	"fmt"
	"net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, World!")
}

func main() {
	http.HandleFunc("/", helloHandler)
	fmt.Printf("Server is running port 8080!")
	http.ListenAndServe(":8080", nil)
}
go run main.go

 

웹 브라우저를 열고 http://localhost:8080에 접속하여 "Hello,World!" 메시지를 확인합니다.


3. 추가 패키지 설치하기

Go의 웹 프레임워크를 사용하고 싶다면, Gorila Mux와 같은 패키지를 설치해줍니다.

go mod init mywebapp # 모듈 초기화
go get -u github.com/gorilla/mux # Gorilla Mux 설치
package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, World!")
}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", helloHandler)
	fmt.Printf("Server is running port 8080!")
	http.ListenAndServe(":8080", r)
}
go run main.go

 

 

GitHub - Koras02/Go-Bloging: https://thinky.tistory.com/category/Back-End/Go

https://thinky.tistory.com/category/Back-End/Go. Contribute to Koras02/Go-Bloging development by creating an account on GitHub.

github.com

 

LIST

'Back-End > Go' 카테고리의 다른 글

[Go] Go 라이브러리를 사용해 HTML 띄우기  (0) 2025.03.06
[Go] 7장 구조체와 인터페이스  (0) 2025.03.04
[Go] 6장 맵  (0) 2025.03.03
[GO] 5장 배열과 슬라이스  (0) 2025.02.28
[Go] 4장 함수(Function)  (0) 2025.02.26